Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dynamically generated form choices in Django
I have a form for submitting new articles in Django, in this form you're allowed to place the post into a 'user_group', just a many many relationship between groups and users. However, you're only allowed to add it into groups you belong to. Using the init function of the form class i can pass in an extra field, and I do get the correct choices I need, however on submit I get an error ''QueryDict' object has no attribute 'all'' I'm not sure whats going wrong, heres my form: class PostForm(BaseModelForm): new_image = forms.ImageField(required=False) #GROUPS = user.groups.all() #group = forms.ChoiceField(choices=GROUPS, required=False ) def __init__(self,groups, *args, **kwargs): super(PostForm, self).__init__(*args, **kwargs) self.fields['group'].queryset = groups class Meta: model = Post fields = ('title','category', 'group', 'text', 'description', 'style') help_texts = { 'group': _('Do you want this published under your account or a group?') } and heres the view where the error is being thrown: @login_required def post_new(request): if request.method == "POST": form = PostForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() return redirect('post_detail', pk=post.pk) else: form = PostForm(groups=request.user.user_groups.all()) return render(request, 'blog/post_edit.html', {'form': form}) This line: form = PostForm(groups=request.user.user_groups.all()) Is where I pass in the choices for groups, which does give you … -
Django 1.7 dumpdata on Windows scrambles unicode characters
I use manage.py dumpdata --format xml --some-more-parameters to export a full dump of the database to xml. The database is MS sql server and I'm using pyodbc as the driver. The dumpdata command is run using PowerShell and since Django 1.7 does not support a --output argument for the dumpdata command I redirect the output into a file using PowerShell. Unfortunately the database contains unicode characters (e.g. country \xd6sterreich) and these characters are scrambled int the export file. Here's what didn't work: ./manage.py dumpdata --format xml > export.xml ./manage.py dumpdata --format xml | out-file -encoding utf8 export.xml ./manage.py dumpdata -format xml | out-file -encoding ANY_OTHER_SUPPORTED_ENCODING export.xml None of these commands work. Umlauts and accents are scrambled and additionally the > export.xml method adds an invalid BOM to the file which will result in ./manage.py loaddata export.xml aborting with an error message when I try to import this on another host. Any suggestions on how I could export the data and preserve the special characters? The same problem exists when using the json or yaml serializers. -
How to disable checkboxes in MultipleChoiceField?
I use MultipleChoiceField in form. It shows me REQUIREMENTS_CHOICES list with checkboxes where user can select and add new requirements to database. Is it possible to disable checkboxes (in my case requirements) which is already in the database? Lets say I have A and C in database so I dont need them. First value in tulpe is symbol of requirement, second value is the name of requirement. models.py: class Requirement(models.Model): code = models.UUIDField(_('Code'), primary_key=True, default=uuid.uuid4, editable=False) symbol = models.CharField(_('Symbol'), max_length=250) name = models.CharField(_('Name'), max_length=250) forms.py: REQUIREMENTS_CHOICES = ( ('A', 'Name A'), ('B', 'Name B'), ('C', 'Name C'), ('D', 'Name D'), ) class RequirementAddForm(forms.ModelForm): symbol = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple, choices=GROUP_REQUIREMENTS_CHOICES,) class Meta: model = Requirement fields = ('symbol',) -
Django - Serve files for download
I have a collection of documents(.pptx files) that I wish to make available for download to users. I am using django for this purpose. I have some parts figured out using these links: having-django-serve-downloadable-files The problem I am facing is in connecting these parts. Relevant code pieces- settings.py file MEDIA_ROOT = PROJECT_DIR.parent.child('media') MEDIA_URL = '/media/' The html template. The variable slide_loc has the file location (ex: path/to/file/filename.pptx) <div class = 'project_data slide_loc'> <a href = "{{ MEDIA_URL }}{{ slide_loc }}">Download </a> </div> The views.py file def doc_dwnldr(request, file_path, original_filename): fp = open(file_path, 'rb') response = HttpResponse(fp.read()) fp.close() type, encoding = mimetypes.guess_type(original_filename) if type is None: type = 'application/octet-stream' response['Content-Type'] = type response['Content-Length'] = str(os.stat(file_path).st_size) if encoding is not None: response['Content-Encoding'] = encoding # To inspect details for the below code, see http://greenbytes.de/tech/tc2231/ if u'WebKit' in request.META['HTTP_USER_AGENT']: # Safari 3.0 and Chrome 2.0 accepts UTF-8 encoded string directly. filename_header = 'filename=%s' % original_filename.encode('utf-8') elif u'MSIE' in request.META['HTTP_USER_AGENT']: # IE does not support internationalized filename at all. # It can only recognize internationalized URL, so we do the trick via routing rules. filename_header = '' else: # For others like Firefox, we follow RFC2231 (encoding extension in HTTP headers). filename_header = 'filename*=UTF-8\'\'%s' … -
How to handle Referer in https post reuest in ionic app with backend django?
I am new to ionic development.I am developing an ionic app with backend django. I have write code for login and signup in django project and I deploy the app into heroku.the django app heroku url working fine. CSRFtoken settings: angular.module('starter.controllers', ['ngCookies']) .config(['$httpProvider', function($httpProvider ) { $httpProvider.defaults.xsrfCookieName = 'csrftoken'; $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken'; }]) For login code: $scope.doLogin = function(){ console.log($scope.loginData); $http({ method: 'POST', url: 'https://django-ionic-api-app.herokuapp.com/api/login/', data: $scope.loginData, dataType: "json" }).then(function successCallback(response) { console.log(response); if(response.statusText == "OK"){ alert("User login successfully!!"); window.localStorage['userdetails'] = JSON.stringify(response.data.user); $scope.userdetails = JSON.parse(window.localStorage['userdetails']); window.location.href = $state.href('app.home'); window.location.reload(); } },function errorCallback(response) { console.log(response) alert(response.data.message) }); }; In web browser, login and signup working good. But when I bulid an apk and test it in mobile, first time login successful but second time getting below error {"detail":"CSRF Failed: Referer checking failed - no Referer."} I have checked with cross origin headers, but I am getting same error. I think I need to handle this Referer error from ionic? but I don't know how to handle this from angularjs(ionic1). Please help me anyone,Thank you. -
Django admin - custom permissions
The problem is simple. I have a 'cars' application. I want to create a user in admin and give him access to admin, but in such a way that user only sees cars app. This part is easy, I can select permissions for view, delete, etc... And only the cars that user himself created through admin. This is what I don't see enabled buy default in admin UI, so I guess I would need to add something to cars/admin.py to show only certain cars if the user belongs to a certain group. -
ValueError: invalid literal for int() with base 10(Django)
error in cmd Code I tried to create a project where to manage a garage, but when I create the model in application"utiliser", I got this problem. Thanks! -
Calling a Stored Procedure using django-mssql
I'm trying to call a stored procedure on a multi-database project I am working with. I have 2 of my stored procedures working, but this particular stored procedure is not working and returns an error: Traceback (most recent call last): File "d:\Projects\Django\AAAVirtualEnv\lib\site-packages\django\core\handlers\exception.py", line 39, in inner response = get_response(request) File "d:\Projects\Django\AAAVirtualEnv\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "d:\Projects\Django\AAAVirtualEnv\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "d:\Projects\Django\AAAVirtualEnv\lib\site-packages\django\views\decorators\csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "d:\Projects\Django\AAAVirtualEnv\lib\site-packages\django\views\generic\base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "d:\Projects\Django\AAAVirtualEnv\lib\site-packages\rest_framework\views.py", line 483, in dispatch response = self.handle_exception(exc) File "d:\Projects\Django\AAAVirtualEnv\lib\site-packages\rest_framework\views.py", line 443, in handle_exception self.raise_uncaught_exception(exc) File "d:\Projects\Django\AAAVirtualEnv\lib\site-packages\rest_framework\views.py", line 480, in dispatch response = handler(request, *args, **kwargs) File "d:\Projects\Django\HRSys\hrs\hrs_api\views.py", line 79, in post result_set = cursor.fetchall() File "d:\Projects\Django\AAAVirtualEnv\lib\site-packages\django\db\utils.py", line 101, in inner return func(*args, **kwargs) File "d:\Projects\Django\AAAVirtualEnv\lib\site-packages\django\db\utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "d:\Projects\Django\AAAVirtualEnv\lib\site-packages\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "d:\Projects\Django\AAAVirtualEnv\lib\site-packages\django\db\utils.py", line 101, in inner return func(*args, **kwargs) File "d:\Projects\Django\AAAVirtualEnv\lib\site-packages\sqlserver_ado\dbapi.py", line 719, in fetchall return self._fetch() File "d:\Projects\Django\AAAVirtualEnv\lib\site-packages\sqlserver_ado\dbapi.py", line 671, in _fetch self._raiseCursorError(FetchFailedError, 'Attempting to fetch from a closed connection or empty record set') File "d:\Projects\Django\AAAVirtualEnv\lib\site-packages\sqlserver_ado\dbapi.py", line 488, in _raiseCursorError eh(self.connection, self, errorclass, errorvalue) File "d:\Projects\Django\AAAVirtualEnv\lib\site-packages\sqlserver_ado\dbapi.py", line 103, … -
Getting 502 Bad Gateway while running the Django application within a docker container?
Those are the following steps I am following to run my application within a docker container . docker run -i -t -d -p 8000:8000 c4ba9ec8e613 /bin/bash docker attach c4ba9ec8e613 my start up script : #!/bin/bash #activate virtual env echo Activate vitualenv. source /home/my_env/bin/activate #restart nginx echo Restarting Nginx service nginx restart # Start Gunicorn processes echo Starting Gunicorn. gunicorn OPC.wsgi:application --bind=0.0.0.0:800 --daemon This setup is working fine in the local machine but not working within the docker . -
Django migrating from MySql to Postgres fails user authentication
I changed the database from MySQL to Postgres. after migrating all data password checking fails. I am using AWS RDS, Is this because of Postgres peer authentication? and if so how can I fix it. -
How to get List from Django Model (instead of Map of fields)
I have a Model called Patient. In this table I have a field:id and condition. So, If I want to get the ids given the condition, I can use this following syntax. ids = list(Patient.objects.filter(condition='sick').values(id)) So the ids will contains a list of map: ids = [{id: 123}, {id=345}, ...] However, instead of map, I want to simply get the list like shown below: ids = [123, 345, ...] How can I achieve this from Django query? Thanks. -
Django: icontains case is sensitive for unicode
I'm making a simple search for my blog. I use an armenian language and when I'm searching it's always sensetive for these letters. Here is a part of my code. Thank you in advance. search_query = get.get('search') query_list = search_query.split() posts = post.objects.filter( reduce(operator.and_, (Q(title__icontains=q) for q in query_list))| reduce(operator.and_, (Q(content__icontains=q) for q in query_list)), ) -
Django unable to find FULLTEXT index in mysql database?
The error that i am getting is OperationalError at /work/filter (1191, "Can't find FULLTEXT index matching the column list") Now what is strange is that i implemented them manually on database as can be seen below and the django code that i have is work_list = Work.objects.filter(work_type=job_type,description__search=query).order_by('-created') paginator = Paginator(work_list,10) the description field has index FULLTEXT from mysql console. Where am i going wrong ? Also i already tried to restart both django as well as database server. -
django-allauth: Verification email not sent on SignUp
Hello I am using allauth with: custom Django user: class Profile(AbstractUser) Custom Signup form: class ProfileForm(UserCreationForm) Alluth account adapter: AccountAdapter(DefaultAccountAdapter) And these are my settings: AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ] # Some really nice defaults ACCOUNT_AUTHENTICATION_METHOD = 'username_email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_ALLOW_REGISTRATION = env.bool('DJANGO_ACCOUNT_ALLOW_REGISTRATION', True) ACCOUNT_ADAPTER = 'strateole2.profiles.adapters.AccountAdapter' # SOCIALACCOUNT_ADAPTER = 'strateole2.profiles.adapters.SocialAccountAdapter' # Custom user app defaults # Select the correct user model AUTH_USER_MODEL = 'profiles.Profile' ACCOUNT_SIGNUP_FORM_CLASS = "strateole2.profiles.forms.ProfileForm" LHello I am using allauth with: custom Django user: class Profile(AbstractUser) Custom Signup form: class ProfileForm(UserCreationForm) Alluth account adapter: AccountAdapter(DefaultAccountAdapter) And these are my settings: AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ] # Some really nice defaults ACCOUNT_AUTHENTICATION_METHOD = 'username_email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_ALLOW_REGISTRATION = env.bool('DJANGO_ACCOUNT_ALLOW_REGISTRATION', True) ACCOUNT_ADAPTER = 'strateole2.profiles.adapters.AccountAdapter' # SOCIALACCOUNT_ADAPTER = 'strateole2.profiles.adapters.SocialAccountAdapter' # Custom user app defaults # Select the correct user model AUTH_USER_MODEL = 'profiles.Profile' ACCOUNT_SIGNUP_FORM_CLASS = "strateole2.profiles.forms.ProfileForm" LOGIN_REDIRECT_URL = '/' LOGIN_URL = 'account_login' # SLUGLIFIER AUTOSLUG_SLUGIFY_FUNCTION = 'slugify.slugify' When I fill the sgnup form and hit signup, the user is created and I it tells me "We have sent an e-mail to you for verification" like this: https://www.dropbox.com/s/0lk4osoeuoswt9k/Capture%20du%202017-04-25%2012-47-27.png?dl=0 But the e-mail is not sent. But then, when I try to log … -
Filtering with elastic-search and django
I've configured elastic search within my django project. The next step is to apply some filtering options of those searches. The content of each search is Cars, so I'd like to be able to filter on Model, Price, Petrol/Diesel etc. Any thoughts on how to achieve this? Thanks, -
Django MySQL Query Json field
I have a MySQL database with a table containing a JSON field called things. The JSON looks like this things = {"value1": "phil", "value1": "jill"} I have collection of objects that I have pulled from the database via my_things = Name_table.objects.values Now, I'd like to filter the my_things collection by one of the JSON fields. I've tried this my_things = my_things.filter(things__contains={'value': 'phil'}) which returned an empty collection. I've also tried my_things = my_things.filter(things={'value': 'phil'}) and my_things = my_things.filter(things__exact={'value': 'phil'}) I'n using Django 1.10 and MySQL 5.7 Thoughts? -
Django html template in a seperate file
My question is more of an etiquette theme rather than anything else. I'm developing a relatively small application that reads XML data and writes to an Oracle DB and outputs to a webpage. I'm reading through the "The Definitive Guide to Django: Web Development Done Right" book, basically because learning something new is fun I recognise more and more requests for Engineers with Django experience. In the book, there is a recommendation to seperate html templates seperately (for example in .html files in its own folder). Are there any advantages to saving seperately the templates as opposed to just leaving a html template embedded in my python script? The template which I'm using is about 15 lines, and uses the data in a generate list to populate the html text, for example: path_to_be_used = desktop_path + 'XURA_output.html' f = open(path_to_be_used, 'w') string = """<html> <head><title>XURA Messaging</title></head> <body> <p>XURA Message contents: the data contained in this page is the Push Notification output retrieved from the XURA server.<br> Upon arrival this data is subsequently written to the Oracle database. """ f.write(string) line1 = "<p><pre>TAG".ljust(28) + "| " + "TEXT".ljust(40) + " </pre>" f.write(line1) for tag in smsreport_list: tagInfo = tag[0] textInfo = … -
Django custom prefetch and conditional annotate
I am using custom prefetch object to get only some related objects, ex: unreleased_prefetch = Prefetch("chants", Chant.objects.with_audio()) teams = Team.objects.public().prefetch_related(unreleased_prefetch) This works well, but I also want to know count of these objects and filter by these. I am happy that I can at the moment use queryset as parameter to Prefetch object (as I heavily use custom QuerySets/Managers). Is there way how I can reuse this query, that I pass to Prefetch object same way with conditional annotate? So far my conditional annotate is quite ugly and looks like this (it does same thing as my original chant with_audio custom query/filter): .annotate( unreleased_count=Count(Case( When(chants__has_audio_versions=True, chants__has_audio=True, chants__flag_reject=False, chants__active=False, then=1), output_field=IntegerField())) ).filter(unreleased_count__gt=0) It works, but is quite ugly and has duplicated logic. Is there way to pass queryset to When same way I can pass it to prefetch to avoid duplications? -
Django cache and usernames
So I have this site (Django 1.8) which has a master template where the name of the logged-in user is displayed, so the template contains {% if user.is_active %} {% trans 'Welcome,' %}{% filter force_escape %}{% firstof user.first_name user.username %}{% endfilter %} {% endif %} So notice it only displays when the user is active. I now setup caching where I use redis as the cache storage: CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://redis:6379/1', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', }, "KEY_PREFIX": "mycache", } } Caching works correctly, but I notice that also that username is cached in the frontend. This means that when the user loggs off, his name is still visible like he is logged in and even worse, sometimes it displays the name of another user that logged in just before and triggered the caching. It is logical of course as I think the caching framework caches the whole page. My question is: how do you deal with this? Do I need some user-based caching of some sorts or are there better ways to avoid this? I mean, there must have been other people encountering the same problem? -
Django DetailView with form for comments
I have this url mapping: url(r'^article/(?P<slug>[-\w]+)/$', views.ArticleView.as_view(), name='article-detail'), and I have this view: class ArticleView(DetailView): model = Article template_name = 'template/article.html' context_object_name = 'article' def get_context_data(self, **kwargs): context = super(ArticleView, self).get_context_data(**kwargs) context['comments'] = self.object.comment_set.filter(approved=True) return context I've already displayed all the approved comments (as you see), but I don't know how to create a comment form inside that ArticleView. I have this ModelForm: class CommentForm(forms.ModelForm): class Meta: model = Comment fields = '__all__' and... Comment model: class Comment(models.Model): author = models.CharField(max_length=100) article = models.ForeignKey(Article, on_delete=models.CASCADE) email = models.EmailField() message = models.TextField(max_length=1000) created_at = models.DateTimeField(auto_now_add=True) approved = models.BooleanField(default=False) The problem with CommentForm is that I don't know how to 'hide' article and approved fields and how to fill article field with the article got in the ArticleView. I've tried to combine FormMixin with DetailView but.. when I submit the comment form, console displays: Method not Allowed (POST). How can I create a form view into ArticleView? If you didn't get something, please ask me, I know my grammar is bad. I will try to be clear as much as possible. Thanks in advance for answers. -
Fail to Deploy the Django App in the Heroku Cloud
I was trying to deploy a Django app in the Heroku following the official instruction. The project structure is as following, It's good to mention that, I can run heroku locally from the src folder, heroku local web. Also the app create works fine, heroku create. While I tried to deploy the app using the command git push heroku master, I get the error message in the terminal, remote: -----> Failed to detect app matching https://codon-buildpacks.s3.amazonaws.com/buildpacks/heroku/python.tgz buildpack remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to sheltered-sea-46201. remote: To https://git.heroku.com/sheltered-sea-46201.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/sheltered-sea-46201.git' What should I need to do to resolve the issue? -
Intersection of two django model?
I have To models and iIwant to find out the common sets of values on the basis of there ids first model:- from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User # WE ARE AT MODELS/UNIVERSITIES class Universities(models.Model): id = models.IntegerField(db_column="id", max_length=11, help_text="") name = models.CharField(db_column="name", max_length=255, help_text="") abbreviation = models.CharField(db_column="abbreviation", max_length=255, help_text="") address = models.CharField(db_column="address", max_length=255, help_text="") status = models.BooleanField(db_column="status", default=False, help_text="") createdAt = models.DateTimeField(db_column='createdAt', auto_now=True, help_text="") modifiedAt = models.DateTimeField(db_column='modifiedAt', auto_now=True, help_text="") updatedBy = models.ForeignKey(User,db_column="updatedBy",help_text="Logged in user updated by ......") class Meta: managed = False get_latest_by = 'createdAt' db_table = 'universities' and the other model:- from __future__ import unicode_literals from django.db import models class NewsUniversityMappings(models.Model): id = models.IntegerField(db_column="id", max_length=11, help_text="") newsMappingId = models.IntegerField( db_column='newsMappingId' ,max_length=11, help_text="") universityId = models.IntegerField( db_column='universityId', max_length=11, help_text="") createdAt = models.DateTimeField(db_column='createdAt', auto_now=True, help_text="") class Meta: managed = False db_table = 'news_university_mappings' now in my views i have created objects for both models:- def add_promoter_news(request, mapping_id=None, news_virtual_id=None): try: university_all_list = Universities.objects.using("cms").all published_university_list = NewsUniversityMappings.objects.using("cms").filter(newsMappingId=news_virtual_id).all() I wanted to finds the common of both the models on the basis of in of universit model and universityId of NewsUniversityMappings.Any help would be appreciated. THanks in advance -
Ajax Requests Slow in Django
I have the following ajax request in my django template: $('#subjects').on('change', function() { var subject = $('#subjects').find(":selected").text(); $.ajax({ type: "GET", url: "/classes/" + term + "/" + subject , // or just url: "/my-url/path/" dataType: "html", success: function(data) { $('#classes').html(data); } }); //remove courses //remove overview //get courses for specified subject //put them under course }); The "subject" id is for a select form like this: <select size="7" class="form-control" id="subjects"> {% for subject in subjects %} <option>{{ subject }}</option> {% endfor %} </select> So, when a subject is changed, I send an ajax request to the server so that I can get the classes for that subject from the database (as there are thousands of classes). However, this takes ~1 second. If a user simply arrows down my list of subjects, then tens of ajax requests will be fired off in a second, causing a backup and slowing down the data being displayed properly. I tried aborting all previous ajax requests before sending another one, but the problem is the server will still process these, so it did not fix the problem. Is there any way to speed this up, and somehow only take 1 second any time a user … -
AJAX not working after deployment
I am facing this problem after putting my website online! The AJAX requests are not being processed at all. I have put a logger in the view function to know whether the view method is being called or not and no, it is not although it gives Success in the front end! When I retry it offline, it works perfectly. The JQuery code: function interactive_search(query) { $.ajax({ url: window.location.href, type: "POST", data: { query: query, csrfmiddlewaretoken: getCookie('csrftoken') }, success: function (json) { receive_neurons(json, true, 'checkbox'); }, error: function (xhr, errmsg, err) { console.log(xhr.status + ": " + xhr.responseText); } }); } The view function @ensure_csrf_cookie def interactive_search(request): log = open('Neurons_search_log.txt', 'a') log.write('Call'+'\n') if request.method == POST: if request.is_ajax(): log.write('Ajax'+'\n') query= request.POST.get('query') retrieved_neurons = search_for_neurons(query); retrieved_neurons_for_ajax = get_neurons_dictionary_for_ajax(retrieved_neurons) return JsonResponse({'neurons': retrieved_neurons_for_ajax}) return render_to_response('neurons_database/pages/interactive_search.html', {}, context_instance=RequestContext(request)) Thank you very much -
Ctype Windows access violation reading 0xBFF3555F
I use Ctype in my Django project but when I use this method : def requete_smartphone(self, bande, debut_a, debut_m, debut_j, fin_a, fin_m, fin_j, sens, fvitesse, fstat, affmes, min, max, moyenne, ecart, algofusion, s_route, vitesse, s_capteurs, s_typeveh, s_marque, s_modele, s_immatriculation, s_pseudo, ecart_moyenne, nombre): """ Permet de faire la requete smarphone avec tout les paramètre qu'elle demande Paramètres : Les même que pour la DLL, suivre ce qui est écrit sur la fiche de la DLL Renvoie """ bande = bande.encode('utf-8') debut_a = int(debut_a) debut_m = int(debut_m) debut_j = int(debut_j) fin_a = int(fin_a) fin_m = int(fin_m) fin_j = int(fin_j) sens = sens.encode('utf-8') fvitesse = fvitesse.encode('utf-8') fstat = fstat.encode('utf-8') affmes = affmes.encode('utf-8') min = min.encode('utf-8') max = max.encode('utf-8') moyenne = moyenne.encode('utf-8') ecart = ecart.encode('utf-8') algofusion = algofusion.encode('utf-8') s_route = s_route.encode('utf-8') vitesse = float(vitesse) s_capteurs = s_capteurs.encode('utf-8') s_typeveh = s_typeveh.encode('utf-8') s_marque = s_marque.encode('utf-8') s_modele = s_modele.encode('utf-8') s_immatriculation = s_immatriculation.encode('utf-8') s_pseudo = s_pseudo.encode('utf-8') ecart_moyenne = float(ecart_moyenne) nombre = nombre.encode('utf-8') DLLFunction = self.libraryBase.requete_smartphone DLLFunction.argtypes = [c_char, c_int, c_int, c_int, c_int, c_int, c_int, c_char, c_char, c_char, c_char, c_char, c_char, c_char, c_char, c_char, c_char_p, c_float, c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, c_float, c_char] DLLFunction.restype = c_bool resultFunction = DLLFunction(bande, debut_a, debut_m, debut_j, fin_a, fin_m, fin_j, sens, fvitesse, fstat, …