Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django TinyMCE ImageLists when using HTMLField
I'm struggling to get the imagelists and linklists working in TinyMCE on Django when using a HTMLField. The documentation says: somefield = forms.CharField(widget=TinyMCE(mce_attrs={'external_link_list_url': reverse('someviewname')}) But I'm using the HTMLField so have to approach it differently. I've looked at How to increase width of editor in django-tinymce HTMLField? and am getting the same init error as suggested. Has anyone been successful with this? -
Remove data from the database when the remove button of a datatable is clicked
I am using a datatable to dispay information for the user and it is generated a delete button per row. I would like to delete the row data from the database when the user click on it. How can I do that? HTML .. $('#id_data').DataTable({ destroy: true, data:data_array_data, "bLengthChange": false, //"bAutoWidth": false, "scrollX": true, "order": [[ 22, "desc" ]], "aoColumns" : [ {title:'User', sWidth: '10px', className:'dt-center' }, {title:'Business', sWidth: '10px', className:'dt-center' }, ... {title:'Revenue', sWidth: '10px', className:'dt-center' }, {title: "",sWidth:'5px',className:'dt-center', "bSortable": false, "mRender": function() { return'<button class="btn btn-danger" id="btn_item_' + itemIndex++ + '"' + ' name="mybtndelete"">Delete</button>'; }, }, ] }); Views @login_required def remove_register(request): instance = MyModel.objects.get(id=pk) "How can I obtain the pk from the datatable?" instance.delete() -
How can I get the current user's group in forms.py in Django?
I have a scenario where i need to pass the logged-in user's groud name and get the list users in that group. forms.py -- in the below code i need to pass the user's group instead of Banglore class UpateTaskMaster(forms.ModelForm): def __init__(self, *args, **kwargs): super(UpateTaskMaster, self).__init__(*args, **kwargs) users = User.objects.filter(groups__name='Banglore') self.fields['processor'].choices = [(user.pk, user.get_full_name()) for user in users] class Meta(): model = TaskMaster fields = ["sid","tasktype","task_title","task_description","datacenter","status","priority","sourceincident","processingteam","duedate","pid","errorincident",'processor'] widgets = { 'sid': forms.TextInput(attrs={'class': 'form-control mr-sm-2'}), 'task_title':forms.Textarea(attrs={'class': 'materialize-textarea'}), 'task_description':forms.Textarea(attrs={'class': 'materialize-textarea'}), 'sourceincident': forms.TextInput(attrs={'class': 'form-control mr-sm-2'}), 'pid': forms.TextInput(attrs={'class': 'form-control mr-sm-2'}), 'errorincident': forms.TextInput(attrs={'class': 'form-control mr-sm-2'}), 'duedate' : forms.TextInput(attrs={'class': 'datepicker'}), } -
How to override value of read-only field in view depending on query param?
I have this model that has a read-only field where I calculate some property. class BlastEvent(Event): tonnes = models.FloatField() blast_type = models.ForeignKey(BlastType) @property def size(self): return self.tonnes / BlastEvent.objects.all().aggregate(Max('tonnes'))['tonnes__max'] This is my serializer: class BlastEventSerializer(serializers.HyperlinkedModelSerializer): size = serializers.ReadOnlyField() included_serializers = {'blast_type': BlastTypeSerializer} blast_type = ResourceRelatedField( queryset=BlastType.objects, related_link_view_name='blastevent-blasttype-list', related_link_url_kwarg='pk', self_link_view_name='blastevent-relationships' ) class Meta: model = BlastEvent fields = ('url', 'id', 'tonnes', 'blast_type', 'size') class JSONAPIMeta: included_resources = ['blast_type'] And this is my view: class BlastEventViewSet(EventViewSet): queryset = BlastEvent.objects.all() serializer_class = BlastEventSerializer Now I need to re-calculate and override this read-only field depending on query parameter. I'm not sure where is the proper place to do it. I tried to do it in get_queryset() method of my view like this: class BlastEventViewSet(EventViewSet): queryset = BlastEvent.objects.all() serializer_class = BlastEventSerializer def get_queryset(self): queryset = self.queryset instrument_id = self.request.GET.get('instrument_id') if instrument_id: for e in queryset: e.size = e.size + Instrument.objects.get(pk=instrument_id).distance return queryset but it doesn't work. It says 'AttributeError: can't set attribute': Traceback: File "/home/nargiza/virtualenvs/myenv/local/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/home/nargiza/virtualenvs/myenv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/nargiza/virtualenvs/myenv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/nargiza/virtualenvs/myenv/local/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "/home/nargiza/virtualenvs/myenv/local/lib/python2.7/site-packages/rest_framework/viewsets.py" in view 86. return self.dispatch(request, … -
overriding django formset initial data dynamically
Ok im new to django So ive got a situation where i want a formset to have dynamic initial data So basically here is what im looking for. each form in the formset to have a different UserID and a set of groups permission which they can choose from based from the initial data here is my form class assignGroupPermissionToUser(forms.ModelForm): UserID = forms.ModelChoiceField(queryset=None) Groups = forms.ModelMultipleCHoiceField(queryset=None, widget=FilteredSelectMultiple("Groups") class Meta: model=User def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) Userid = kwargs.pop("UserID") self.fields['UserID'].queryset =User.objects.get(UserID=Userid) Permissions = kwargs.pop("Groups") listofPermission = None for each perm in permission: listofPermission |= Permissions.objects.filter(GroupID=perm) self.fields['Groups'].queryset = listofPermission the data i wanna pass is built into a list like so it is called completeList > completeList =[['13452',{'group1':'Admin','group2':'FrontDesk'}],['3532','group1':'Supervisors','group2':'ReadOnly;}]] where the first value in each nested loop is the UserID, and the dictionary is the groups they can choose from. override method in View.py .... form = assignGroupPermissionToUser() assignment = formset_factory(form,extra=0) formset = [ assignment.__init__(completeList[x][0],completeList[x][1]) for x in range(len(completeList))] then i get an error that str object has no 'is_bound' field line 58 of formset.py im trytin to get this data to show up on each form and based on the user it will be all different but everything i try to override it fails … -
Django admin panel - Inlines do not show on production server, but do show on local server
Recently I started using the inline functionality for Django admin panels. It just makes it so much easier to add objects. The picture below shows that it allows an admin to add a module while creating a training: Django admin panel with working inlines However, once I push the code to production, the inlines functionality stops working. It simply does not show. My server makes use of Gunicorn and Nginx. Initially I thought that Nginx does not know where to find the static files, but this is not the problem. However, if I run a server via Django with python manage.py runserver 0.0.0.0:8001, then it does work. Additionally, if I run the server via Gunicorn by binding it to 0.0.0.0:8001, then it works as well. This makes me think that the problem is Nginx, but I have no idea where to search. Please help me out :). Kind regards, Nicky -
Django Admin ChoiceField and Button submit to custom admin site (A form in a form)
I would like to generate a contract (as a printable html file) out of the change form of a customer (defined as model) in the django.contrib.admin interface. This contract should be displayed as html file in a different view. So my idea is to have a Dropdown (forms.ChoiceField) with a Submit button in the admin form of a model. If you click on the button then a custom admin site (or HttpResponse, doesn't matter now) will be opened depending on the selected choice. So for example, if I select "Contract one" and click on the button, a page with the template from contract one will be displayed in a new page. But all this should be inside the change_forms.html in a seperate fieldset. What I have so far: A ModelForm with an extra field 'contract' and rendering the button with url reverse as forced html output. admin.py class AnimalAdmin(admin.ModelAdmin): form = AnimalForm list_display = ( 'name', 'customer', ) ordering = ('name',) fieldsets = ( (None, { 'fields': ( ('name', 'species'), ('customer', 'breed'), ) }), (_('Vertrag'), { 'fields': ( ('contract'), ('animal_contract'), ) }), ) readonly_fields = ('animal_contract',) def process_contract(self, request, animal_id, *args, **kwargs): return self.process_action( request=request, animal_id=animal_id, action_title='Contract Generation', ) def … -
What's difference between url() and reverse() methods in Django?
I have some method, and after successful form submitting i need to make some redirect to another page. How can i do this? return HttpResponseRedirect(reverse('goods:results', args=(item.id,))) or return HttpResponseRedirect(url('polls:results', question.id))? What's the main difference by using these two ways? -
Managing state and transitions
I need to implement a standard workflow with three linear steps to handle, i.e. Select Plan & Preference, Personal Information, and Review & Payment. I know three available workflows with python3 and Django, but I think it is overkill for what I am going to do. Select Plan & Preferences: A client may choose one plan as well as some craft products. Personal Information: A client will fill fields related to where he lives, phone number, first name, last name, email, ... Review & Payment : Create an account if necessary, Review his/her order and make the payment related to the current order. Availabe Workflow - With Python 3 Maybe the solution is to implement a custom workflow, but I am a bit confused how to do it. I need a user follows some views step by step. How to check what is the next view that the user should go? Could someone explain to me roughly how can I do it? Does the following website is a great solution for that little workflow? P.S. I am working with Django 1.11 and python 3.4. -
Django - "IOError: [Errno 9] Bad file descriptor" when loaddata a fixture during tests
Traceback (most recent call last): File "py2env/local/lib/python2.7/site-packages/django/test/testcases.py", line 1036, in setUpClass 'database': db_name, File "py2env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 131, in call_command return command.execute(*args, **defaults) File "py2env/local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "py2env/local/lib/python2.7/site-packages/django/core/management/commands/loaddata.py", line 69, in handle self.loaddata(fixture_labels) File "py2env/local/lib/python2.7/site-packages/django/core/management/commands/loaddata.py", line 109, in loaddata self.load_label(fixture_label) File "py2env/local/lib/python2.7/site-packages/django/core/management/commands/loaddata.py", line 198, in load_label fixture.close() IOError: [Errno 9] Bad file descriptor The size of the fixture is 24KB. The exception happens when running tests and happens sporadically. Django 1.11.8 Mac OSX & Linux Note: Wrapping 'loaddata.py, line 198' with try & catch IOError. Setting a breakpoint and continuing immediately prevents the exception. Like this: try: fixture.close() except IOError as e: import pdb; pdb.set_trace() Overriding loaddata command as suggested here didn't help. -
That page number is less than 1 Django
I have read almost all the thread related to a similar error message and none of them offered a solution to my problem. I a story and for each story there are chapters. The idea is that there will be a chapter per page but I keep getting the same error message "EmptyPage at /story/1/page/1/" when I try pagination. I have multiple chapters for each story and I still get page number is less than 1. views.py def post(request, id_story, page=1): story = Story.objects.get(id=id_story) chapters = story.chapter_set.all() paginator = Paginator(chapters, 1) try: chapters = paginator.page(page) except PageNotAnInteger: chapters = paginator.page(1) except EmptyPage: chapters = paginator.page(paginator.num_pages) return render(request, 'single.html', {'story': story, 'chapters': chapters}) models.py class Story(models.Model): Lang =( ('LA', '-LANGUAGE-'), ('Ar', 'ARABIC'), ('Ot', 'OTHER') ) title = models.CharField(max_length=250, null=False) author = models.ForeignKey(User, on_delete=models.CASCADE) summary = models.TextField(max_length=1000, null= False) pub_date = models.DateField(auto_now_add=True, blank=False, null=False) update_time = models.DateField(null=True) has_chapter = models.BooleanField(default=False, editable=False) lang = models.CharField(choices=Lang, default=Lang[0], max_length=3) story_cover = models.FileField() def __str__(self): return self.title + " - " + self.author.username class Chapter(models.Model): story = models.ForeignKey(Story, on_delete=models.CASCADE) chapter_number = models.IntegerField(editable=False, default=1) title = models.CharField(max_length=250, null=True) chapter = models.TextField() def save(self, *args, **kwargs): number = Chapter.objects.filter(story=self.story).count() self.chapter_number = number + 1 story = self.story if … -
Django admin list_display model method
I have this model.py: class Topping(models.Model): name = models.CharField(max_length=32) def __str__(self): return self.name class Base(models.Model): name = models.CharField(max_length=32) slug = models.SlugField(primary_key=True) class Advanced(models.Model): toppings = models.ManyToManyField(Topping) class Mymodel(Base, Advanced): ... def toppings_list(self): list_top = Advanced.toppings return list_top I want to show the list of toppings (preferably formatted, so a list only of the field name of the Topping model) in my Admin, so: class MymodelAdmin(admin.ModelAdmin): #list_display = (..., model.Mymodel.toppings_list(), ...) #Error: missing 1 required positional argument: 'self' #list_display = (..., model.Mymodel.toppings_list(self), ...) #Error: self is not definited list_display = (..., model.Mymodel.toppings_list, ...) #Gibberish: <django.db.models.fields.related_descriptors.ManyToManyDescriptor object at 0x0387FFD0> Only the last one works but don't gives nothing useful. I tried these too (I want format the list before to display): class MymodelAdmin(admin.ModelAdmin): mylist=model.Mymodel.toppings_list #I don't change nothing for now #mylist=[t for t in model.Mymodel.toppings_list] #Error: 'function' object is not iterable list_display = ('mylist') #core.Topping.None again, the last one works but don't gives nothing useful (also Topping isn't None) Thank you -
How do I make a input from the user to search for something in django/python?
I'm relatively new in python/django thing. Having 3 models with some fields for example: class Card(models.Model): id = models.AutoField(primary_key=True) cardtype_id = models.CharField(max_length=10) holder_name = models.CharField(max_length=100) card_number = models.IntegerField(default=0) email = models.EmailField(blank=True) birthday = models.DateField(blank=True, default=None) created = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(default=timezone.now) strip = models.CharField(max_length=20, default="strip") def __str__(self): return self.holder_name class Transaction(models.Model): id = models.AutoField(primary_key=True) description = models.CharField(max_length=100) class CardTransactions(models.Model): card = models.ForeignKey(Card, on_delete=models.CASCADE) transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE) value = models.DecimalField(max_digits=7, decimal_places=2, blank=True) value_date = models.DateTimeField(default=timezone.now) created = models.DateTimeField(default=timezone.now) description = models.CharField(max_length=200, blank=True) table_value = models.DecimalField(max_digits=7, decimal_places=2, blank=True) discount = models.DecimalField(max_digits=7, decimal_places=2, blank=True) net_value = models.DecimalField(max_digits=7, decimal_places=2, blank=True) doc_number = models.CharField(max_length=20, blank=True) How can I ask the user to input, for example, the "card_number" and print out the "description" on a HTML page? -
'TemplateDoesNotExist at /' error during local development
I am following two scoops of django and mozilla tutorial for deploying my app. I set up a virtual env and base setting, local setting,etc and when i ran the command : ./manage.py runserver 0:8000 --settings=Books.settings.local the browser showed the error, template home not found... I think there might be some problem due to the env, i am not sure. base.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '2z9y' # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' ALLOWED_HOSTS = ['127.0.0.1', 'localhost','https://hackingonlineeducation.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #third party apps 'star_ratings', 'crispy_forms', #my_apps 'newsletter', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Books.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'Books.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, … -
Virtual environment not activating - unauthorized access error
I'm trying to activate a virtual environment using the following in PowerShell env_project1\scripts\activate I'm following instructions from an online tutorial called the django book. But this gives me the following error env_project1\scripts\activate : File C:\Users\Admin\Documents\project1\env_project1\scripts\activate.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170. At line:1 char:1 + env_project1\scripts\activate + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : SecurityError: (:) [], PSSecurityException + FullyQualifiedErrorId : UnauthorizedAccess This used to work when I was using django from the same tutorial a few months ago, and I'm confused as to how to fix this. The link in the instructions just redirects to msn. Thanks! -
Django css file is not working
I'm new in Django and get problem. I have: STATIC_URL = '/static/' STATIC_ROOT = '/static/' at my settings.py, have Project/mainapp/static folder and css/header.css inside that folder. Also i have {% load staticfiles %} <link rel="stylesheet" href="{% static 'css/header.css' %}" type="text/css"> at my header html. Browser tries localhost/static/css/header.css but find nothing there. What am i doing wrong? Thanks! -
django celery error "Apps aren't loaded yet" All recommended fixes I've tried has failed - I believe I have settings configured incorrectly somewhere
My goal is to use celery to use celery to automatically run script on my site each day. I followed the instructions for first steps with Django here. After I have all of my setting configured, I use celery -A project worker --loglevel=info and the server seems to start fine. When I attempt to import the tasks app it can't find the module, it says it doesn't exist, but it works if I explicitly call folder.tasks. If I call function.delay() I get the following error: raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I do a few searches and try adding a recommendation of using Django-Q. After I put it at the bottom of installed apps and attempt to python manage.py migrate celery, I get the same AppRegistryNotReady error as before but when I attempt to start celery. I tried adding import django | django.setup() in my settings.py as recommended by someone. How can I fix this issue? here is the traceback C:\Users\Jup\PycharmProjects\Buylist_django>python manage.py migrate Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 216, … -
Related Field got invalid lookup :exists
In my database, I have a Photo class, that I use as a foreignkey to other classes. These are two examples of such. class SubstancePointsLabel(ResultBase): #: photo being labeled photo = models.ForeignKey(Photo, related_name='substance_points_labels') class SubstancePoint(EmptyModelBase): #: photo photo = models.ForeignKey(Photo, related_name='substance_points') The only difference in these instances the ResultBase and EmptyModelBase but nothing in seems (to me) to be the cause. class EmptyModelBase(models.Model): """ Base class of all models, with no fields """ def get_entry_dict(self): return {'id': self.id} def get_entry_attr(self): ct = ContentType.objects.get_for_model(self) return 'data-model="%s/%s" data-id="%s"' % ( ct.app_label, ct.model, self.id) def get_entry_id(self): ct = ContentType.objects.get_for_model(self) return '%s.%s.%s' % (ct.app_label, ct.model, self.id) class Meta: abstract = True ordering = ['-id'] class ResultBase(UserBase): """ Base class for objects created as a result of a submission """ #: The MTurk Assignment that the user was in when this record was created mturk_assignment = models.ForeignKey( 'mturk.MtAssignment', null=True, blank=True, related_name='+', on_delete=models.SET_NULL ) #: True if created in the mturk sandbox sandbox = models.BooleanField(default=False) #: This has been marked by an admin as invalid or incorrect AND will be #: re-scheduled for new labeling. This can happen when an experiment is #: changed and things need to be recomputed. invalid = models.BooleanField(default=False) #: The method … -
The fun of django form datetime pickers
So I've explored several ways of trying to add a date time picker to my django forms. It's been ugly. I've found one that I've gotten to work well here. It looks good and works...sort of. The new problem becomes I'm rendering my datetime fields in a formset, so I need to add an index value to the id field of the element. That means something like clock_in = forms.DateTimeField(widget=DateTimePicker(attrs={'class': 'form-control', 'id': 'datetimepicker1'})) will not work. datetimepicker# needs to be indexed for each element the formset generates. Can I even do that? If so, how. Are there easier\better ways to graphically select a datetime for input (like the django admin)? -
Using Pika with Django (Event-based microservice using django rest framework)
anyone here has experience implementing pika with Django? I am basically running an event-based microservice using django rest framework. And using RabbitMQ as the message bus. I know the default library to use in this case would be Celery, but I am looking for a lighter version where I can just implement a simple pub / sub on the messages. Has anyone implemented such a service using pika before? My question is more how do you spawn pika as a separate process together with Django? Or is there a more elegant solution out there? Thanks in advance. -
Django sitemap.xml doesn't show my domain
I'm creating a sitemap.xml file through from django.contrib.sitemaps.views import sitemap but it actually comes out with the file in that way below. My domain is replaced with example.com and I can't fix it because the file is not editable in the usual way. <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc>http://example.com/</loc> <changefreq>never</changefreq> <priority>0.5</priority> </url> <url> <loc>http://example.com/recruit/</loc> <changefreq>never</changefreq> <priority>0.5</priority> </url> <url> <loc>http://example.com/contact/</loc> <changefreq>never</changefreq> <priority>0.5</priority> </url> <url> <loc>http://example.com/success/</loc> <changefreq>never</changefreq> <priority>0.5</priority> </url> </urlset> Any help would be appreciated!! -
how to pass the url of image clicked on my html file to my python function in views.py Django
i want to pass the url of the image that was selected by the user in my python function views.py because my python function will process the image that was selected by the user. this is my html command <!DOCTYPE html> <html> <head> <link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" /> <script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script> <meta charset=utf-8 /> <title>JS Bin</title> <!--[if IE]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <style> article, aside, figure, footer, header, hgroup, menu, nav, section { display: block; } </style> </head> <body> <input type='file' onchange="readURL(this);" /> <img id="blah" src="#" alt="your image" /> <script> function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#blah') .attr('src', e.target.result) .width(150) .height(200); }; reader.readAsDataURL(input.files[0]); } } </script> </body> </html> and here is the function on my python def predict(): img = cv2.imread('C:/Users/HABITUS/Desktop/arvin files/download.jpg') #the url of the image selected must be here!! img = cv2.resize(img, (600, 600)) enhancer = Image.fromarray(img) enhancer = ImageEnhance.Contrast(enhancer) enhanced = enhancer.enhance(1.5) enhancer1 = ImageEnhance.Brightness(enhanced).enhance(1.3) convert = scipy.misc.fromimage(enhancer1) imgM = cv2.medianBlur(convert, 5) # blurring and smoothening kernel = np.ones((5, 5), np.uint8) erosion = cv2.erode(imgM, kernel, iterations=1) dilation = cv2.dilate(erosion, kernel, iterations=1) blur = cv2.GaussianBlur(convert, (15, 15), 10) grayscaled = cv2.cvtColor(imgM, cv2.COLOR_BGR2GRAY) retval2, … -
ejabbered xmpp server chat integration with django api
I am trying to integrate ejabbered with django api. I am unable to understand which package to use. Can any one tell me the steps to integrate jabbered with django user table. I also want to know its flow to establish chat in app end. I am unable to figure out the package to use in django for xmpp. Any help will be appreciated. I know that i have to include the ejabbered password and username in user table. -
How to set limit of redisearch default limit is 10 . i want to set 50
from redisearch import Client client = Client('myIndex') res = client.search(search_key)# i want 50 results here -
Django: Modify an Active Directory User
So I am trying to modify a user in my active directory. As of now I can log in as an AD-user but when I try to edit my profile, it does not implement in the AD. I made a connection with a user that has reading an writting permissions. AUTH_LDAP_SERVER_URI = "ldap://192.168.1.12" AUTH_LDAP_BIND_DN = "user" AUTH_LDAP_BIND_PASSWORD = "password" AUTH_LDAP_CONNECTION_OPTIONS = { ldap.OPT_DEBUG_LEVEL: 1, ldap.OPT_REFERRALS: 0 } AUTH_LDAP_USER_SEARCH = LDAPSearch("DC=sb,DC=ch", ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)") # Set up the basic group parameters. AUTH_LDAP_GROUP_SEARCH = LDAPSearch("DC=sb,DC=ch", ldap.SCOPE_SUBTREE, "(objectClass=group)") AUTH_LDAP_GROUP_TYPE = NestedActiveDirectoryGroupType() # What to do once the user is authenticated AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail" } AUTH_LDAP_USER_FLAGS_BY_GROUP = { "is_active": "CN=ipa-users,cn=users,DC=sb,DC=ch", "is_staff": "CN=ipa-users,cn=users,DC=sb,DC=ch", "is_superuser": "CN=ipa-users,cn=users,DC=sb,DC=ch" } # This is the default, but be explicit. AUTH_LDAP_ALWAYS_UPDATE_USER = True # Use LDAP group membership to calculate group permissions. AUTH_LDAP_FIND_GROUP_PERMS = True # Cache settings AUTH_LDAP_CACHE_GROUPS = True AUTH_LDAP_GROUP_CACHE_TIMEOUT = 3600 AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) So what and where do I have to set or get anything? This is my edit_profile.html: <form method="post"> {% csrf_token %} <label for="first_name">Vorname </label> <input style="margin-bottom: 1em;" id="first_name" class="form-control" type="text" name="first_name" value="{{ user.first_name }}"><br> <label for="last_name">Nachname </label> <input style=" margin-bottom: 1em;" id="last_name" class="form-control" type="text" name="last_name" value="{{ …