Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Gunicorn not running can't connect to sock file
I've got a gunicorn script that fails to load. Here's it's code [Unit] Description=gunicorn daemon After=network.target [Service] User=sammy Group=www-data WorkingDirectory=/home/sammy/revamp ExecStart=/home/sammy/revamp/revampenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/sammy/revamp/revamp.sock revamp.wsgi:application [Install] WantedBy=multi-user.target and the response from status ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Wed 2017-07-19 14:17:56 UTC; 2min 1s ago Process: 26564 ExecStart=/home/sammy/revamp/revampenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/sammy/revamp/revamp.sock revamp.wsgi:application (code=exited, status=1/FAI Main PID: 26564 (code=exited, status=1/FAILURE) Jul 19 14:17:51 samuel-pc gunicorn[26564]: [2017-07-19 14:17:51 +0000] [26564] [INFO] Starting gunicorn 19.7.1 Jul 19 14:17:51 samuel-pc gunicorn[26564]: [2017-07-19 14:17:51 +0000] [26564] [ERROR] Retrying in 1 second. Jul 19 14:17:52 samuel-pc gunicorn[26564]: [2017-07-19 14:17:52 +0000] [26564] [ERROR] Retrying in 1 second. Jul 19 14:17:53 samuel-pc gunicorn[26564]: [2017-07-19 14:17:53 +0000] [26564] [ERROR] Retrying in 1 second. Jul 19 14:17:54 samuel-pc gunicorn[26564]: [2017-07-19 14:17:54 +0000] [26564] [ERROR] Retrying in 1 second. Jul 19 14:17:55 samuel-pc gunicorn[26564]: [2017-07-19 14:17:55 +0000] [26564] [ERROR] Retrying in 1 second. Jul 19 14:17:56 samuel-pc gunicorn[26564]: [2017-07-19 14:17:56 +0000] [26564] [ERROR] Can't connect to /home/sammy/revamp/revamp.sock Jul 19 14:17:56 samuel-pc systemd[1]: gunicorn.service: Main process exited, code=exited, status=1/FAILURE Jul 19 14:17:56 samuel-pc systemd[1]: gunicorn.service: Unit entered failed state. Jul 19 14:17:56 samuel-pc systemd[1]: gunicorn.service: … -
Django order by many to many field
How can I order a listview's queryset according to this criteria? Two models from django.db import models class Submission(models.Model): date = models.DateTimeField(default=timezone.now) mae = models.IntegerField(null=True) class Submitter(models.Model): ... submissions = models.ManyToManyField(Submission, blank=True) Now, in the list view I need to display all users, their submission count, ordered by the highest MAE (descending). This is fine I could use queryset = Submitter.objects.annotate(max_mae=Max("submissions_mae")).order_by("-max_mae") and just use {{ object.submissions.count }} in the template for the count. However, here's what I don't know how to do. How do I order by only the latest submission, date descending, in each users many to many field That is I want the annotate's max to only consider submissions.most_recent -
deploying bootstrap on heroku with django
I am having trouble with deployment of twitter bootstrap on my heroku client. My html code is not showing like it should (alignment, special table layouts, etc) All is working locally, but i assume it has to do with the static files that don't get transferred correctly. This is the static file structure, but have a look how it looks like when i open the "source chrome console" on my live heroku verson. View of how the folder structure should be Folder structure of deployed code on heroku It looks like some folders are "stitched" one to another. what could be my issue? should i avoid "-" and "_" in my file names? thanks for the help. -
marking a variable for translation in django
I have a view file in django like this var_name = "This value can change dynamically based on third party calls" def some_view(request): message = _("This gets translated") message = _(var_name) While doing make messages in django, I get the first text in django.po file as expected, but the second one doesn't show up. Can I make it show up. OR can I log the actual text for future reference stating that such and such text is not marked for translation in the PO file. Thanks -
Django Error Message From django.db Models To Admin
I'm using DRF to create an API backend. Now, I want to enforce certain validation rules while saving the models from the admin. I'm using viewset and can override when called from the rest framework. But when I validate model by overriding the save() method, it can't send any error message to the admin as it doesn't have any request parameter. The scenario is like this: from django.db import models class PatientCaregiver(models.Model): name = models.CharField(max_length=200, null=True, blank=True) email = models.CharField(max_length=200, null=True, blank=True) def save(self, *args, **kwargs): # do some processing # return some error or success msg(how?) I know that I can send the error message with the following code: from django.contrib import messages messages.error(request,'Error message') But as you can see, in my save() model, I don't have the request parameter. So, how to send any error message from the save() model to the admin? -
How can I get rid of keyword QuerySet in retrun value from model in django
I have a model with custom properties. In my admin I display the return value from the model. The return values from all properties start with the following words in each record. <QuerySet [ I am trying to get rid of the <QuerySet [ from showing up in every record as shown in the image? When I display the return value from get_followers, get_following, get_friends, all the return values contain <QuerySet [ Any idea how I can do this? class Application(TimeStampModel): name = models.CharField(verbose_name='CI Name', max_length=100, unique=True) relationships = models.ManyToManyField('self', through='Relationship', symmetrical=False, related_name='related_to') def get_following(self): return self.get_relationships(RELATIONSHIP_FOLLOWING) def get_followers(self): return u'%s' % self.get_related_to(RELATIONSHIP_FOLLOWING) def get_friends(self): return self.relationships.filter( to_apps__status=RELATIONSHIP_FOLLOWING, to_apps__from_application=self, from_apps__status=RELATIONSHIP_FOLLOWING, from_apps__to_application=self) def __str__(self): return "{}".format(self.name) RELATIONSHIP_FOLLOWING = 1 RELATIONSHIP_BLOCKED = 2 RELATIONSHIP_STATUSES = ( (RELATIONSHIP_FOLLOWING, 'Following'), # Following: denotes the relationship from the user, i.e. following (RELATIONSHIP_BLOCKED, 'Blocked'), ) -
Same filename in differen Django apps opens the same template
Currently I create a Django Website. I created one app. project --app ----templates ------index.html ----url.py ----views.py --project ----templates ------index.html ----url.py ----views.py in both url.py i create the url-pattern url(r'^', views.index, name="index"), and the url.py file in project contains url(r'^heatingControll/', include('heatingControll.urls')),. In both views I add the function : def index(request): template = loader.get_template('index.html') context = {} return HttpResponse(template.render(context, request)) As I understand, Django will opens the index.html from the app/template folder by run 127.0.0.1:8000/app, and by run 127.0.0.1:8000 the index.html from the project/templatefolder. But it runs each time the app/templates/index.html file. I strongly belive that it should be possible to use the same directory name in serveral apps. What could be my problem? -
How to replace ../ from the path using python and Django
I need some help. I need to replace the up directory path like ../ from the file path using Python. I am explaining my code below. filepath=nest/../../upload/ or filepath = ../../../../upload/ Here I need to remove those ../ from that file path using Python. Please help. -
Tweeter Oauth:You are authenticated as XXX, but are not authorized to access this page. Would you like to login to a different account?
I have created just a simple django app to login using tweeter, but when i try to login from my app I get this message "You are authenticated as xxx, but are not authorized to access this page. Would you like to login to a different account?" enter image description here I have tried to login with account I used to create the app and different account, but the result is the same. What could be the solution to this? I am using django and django-allauth library -
Graphs: Which one to use for recommendation Engine
I need to build a recommendation engine. We are using Python and Django in project. I have User objects and each user has different properties like Story etc. Typically we are thinking for recommending some stories to a User etc. For that I am trying to create a graph. I decided upon using NetworkX to build the same. But going over the documentation I feel limited and overwhelmed. There are N number of graphs suggested. Clustered, Stocastic and what not. http://networkx.readthedocs.io/en/networkx-1.10/reference/generators.html I have never heard about them and other associated terminology. Just aware about typical grad school basics of Graphs. Can somebody suggests some basic read through for me to get acquainted. Also not sure about NetworkX was thinking over Neo4jDjango etc. -
Loading Multiple Images on a Mac
I'm using the following Javascript to load multiple images onto the screen. window.onload = function(){ //Check File API support if(window.File && window.FileList && window.FileReader) { var filesInput = document.getElementById("id_file_field"); filesInput.addEventListener("change", function(event){ var files = event.target.files; //FileList object var output = document.getElementById("result"); for(var i = 0; i< files.length; i++) { var file = files[i]; //Only pics if(!file.type.match('image')) continue; var picReader = new FileReader(); picReader.addEventListener("load",function(event){ var picFile = event.target; var div = document.createElement("span"); div.innerHTML = "<img class='image-thumbnail' draggable='true' ondragstart='drag(event)' id='drag"+i+"' src='" + picFile.result + "'" + "title='" + picFile.name + "'/>"; output.insertBefore(div,null); }); //Read the image picReader.readAsDataURL(file); } }); } else { console.log("Your browser does not support File API"); } }; This is then passed to Django when the form is submitted and the files are saved using: file_form = FileFieldForm(request.POST, request.FILES) files = request.FILES.getlist('file_field') if file_form.is_valid(): for f in files: m = MyImages ( image = f, item = item ) m.save() I works fine for Linux (Chrome, Firefox and Opera tested) and Windows PCs (Edge and Chrome tested) but it is not working on Firefox (48.0.2), on a Lion Mac (10.7.5). For the Mac it is only loading the first image. Is there something strange about the Mac I should … -
How to pass request.user in ajax call when using django?
I am trying to send json data to django backend on my website.When I wanted to get user object in the view function,I got this "AnonymousUser" error. Below is my code: My api view: @api_view(['GET','POST']) def add_vote(request): if request.method =='POST': user = request.user serializer = VoteSerializer(data=request.data) if serializer.is_valid(): instance = serializer.save(creator=user) return redirect(instance) return Response(serializer.errors) if request.method == 'GET': votes = VoteTitle.objects.all() serializer = VoteSerializer(votes,many=True) print(request.user) return Response(serializer.data) This is my send function(a react class function): sent_json(){ let send_json = { title:this.state.title, subjects:[], }; send_json.subjects = this.state.subjects.map((object) => ({name:object})); send_json = JSON.stringify(send_json); console.log(send_json); let csrftoken = Cookies.get('csrftoken'); console.log(csrftoken); let header = { "method":'POST', "body" :send_json, "headers":{ "X-CSRFToken": csrftoken, "Accept": "application/json", "Content-Type": "application/json", } }; fetch('http://127.0.0.1:8000/voteapp/add/',header).then(function(response){ console.log(response); return response.json(); }).then(function(response){ console.log(response); }).catch(function(error){ alert(error); }); } Error message shown in the django backend : Internal Server Error: /voteapp/add/ Traceback (most recent call last): File "/Users/phil/Desktop/Web-Development/mini-blog/env/lib/python3.5/site-packages/django/core/handlers/exception.py", line 42, in inner response = get_response(request) File "/Users/phil/Desktop/Web-Development/mini-blog/env/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/phil/Desktop/Web-Development/mini-blog/env/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/phil/Desktop/Web-Development/mini-blog/env/lib/python3.5/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/Users/phil/Desktop/Web-Development/mini-blog/env/lib/python3.5/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/Users/phil/Desktop/Web-Development/mini-blog/env/lib/python3.5/site-packages/rest_framework/views.py", line 489, in dispatch response = self.handle_exception(exc) File … -
Uploading to different folders depending on choice - Django
I've been reading the django documentation and I'm trying to create a set of choices. Depending on which choice a user chooses, a file will save in a different folder. Though I can't seem to find a way for this to work. I've currently got this as my model: from django.db import models class Document(models.Model): Name = models.CharField(max_length=25, blank=True) Week_1 = 'Week1' Week_2 = 'Week2' Week_3 = 'Week3' Week_4 = 'Week4' Weekly_Choices = ( (Week_1, 'Week_1'), (Week_2, 'Week_2'), (Week_2, 'Week_3'), (Week_2, 'Week_4') ) Week = models.CharField(max_length=10, choices=Weekly_Choices, default=Week_1, blank=False) docfile = models.FileField() if Week.choices == Week_1: docfile.upload_to = 'documents/'+ Week_1 + '/' + 'Mentee' Though, I don't know why this doesn't work - sorry I'm still a bit new to Django and Python. I've looked into it more and I know there is a Model.get_FOO_display() function but that's not what im looking for. In addition I also looked at django-choices, though the 'get_choice' function outputs a dictionary type. I was hoping there might be an easier way which im missing? Any help would be useful - thanks :D -
Django import / export: ForeignKey fields return None
Using Django Import/Export, I have problems importing foreign key fields into my Django models. Specifically, I have three fields in my model that I want to import (the fourth one—participant—having a default value, so we can ignore that one), of which one is an IntegerField and the two other are ForeignKey fields. All three fields are converted to numeric format before importing. However, the ForeignKey fields can't read these values and instead import NaN (presumably because I have set these model fields to null=True. I have tried multiple of the solutions on similar questions, but they did not solve this problem. What am I doing wrong here? models.py class User(auth.models.User,auth.models.PermissionsMixin): def __str__(self): return "@{}".format(self.username) class Forskningsresultater(models.Model): id = models.IntegerField(primary_key=True) authors = models.ManyToManyField(settings.AUTH_USER_MODEL, through='PersonRes', blank=True,related_name='authors',verbose_name="Authors") ... (plus irrelevant fields for this question) class PersonRes(models.Model): id = models.IntegerField(primary_key=True) user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,verbose_name="user") forskningsresultater = models.ForeignKey(Forskningsresultater,on_delete=models.CASCADE, null=True,verbose_name="forskningsresultater") participant = models.BooleanField(default=True) def __str__(self): return "{}. Result {}: {}".format(self.id,self.forskningsresultater, self.user) admin.py from import_export import widgets, fields, resources class PersonResResource(resources.ModelResource): user = fields.Field(column_name='user_id', attribute='user', widget=widgets.ForeignKeyWidget(settings.AUTH_USER_MODEL, 'id')) forskningsresultater = fields.Field(column_name='forskningsresultater_id', attribute='forskningsresultater', widget=widgets.ForeignKeyWidget(Forskningsresultater, 'id')) class Meta: model = PersonRes fields = ('id','user','forskningsresultater','participant',) from import_export.admin import ImportExportModelAdmin class PersonResAdmin(ImportExportModelAdmin): class Meta: resource_class: PersonResResource admin.site.register(PersonRes,PersonResAdmin) myscript.py ... df_persres[['A']] = df_persres[['A']].apply(pd.to_numeric) df_persres[['B']] … -
Django S3 Boto Permission Denied Error
Everything works fine on the S3 server for collecting static files and serving them. However, whenever trying to upload media files the user has set a permission denied (403) error is raised. On the model ImageField's I am using storage=OverwriteStorage(). Is this conflicting with the default s3BotoStorage? If so, how do I modify OverwriteStorage so that it works on both local and production (with S3)? class OverwriteStorage(FileSystemStorage): def get_available_name(self, name, max_length=None): filename, ext = os.path.splitext(name) if "-new" in filename or "-old" in filename: filename = filename[:-4] new_name = filename + "-new" + ext old_name = filename + "-old" + ext old_path = os.path.join(settings.MEDIA_ROOT, old_name) new_path = os.path.join(settings.MEDIA_ROOT, new_name) if os.path.exists(old_path) and os.path.exists(new_path): os.remove(old_path) os.rename(new_path, old_path) name = new_name elif os.path.exists(old_path): name = new_name else: name = old_name return name settings.py (production) AWS_FILE_EXPIRE = 200 AWS_PRELOAD_METADATA = True AWS_QUERYSTRING_AUTH = True DEFAULT_FILE_STORAGE = '.....MediaRootS3BotoStorage' STATICFILES_STORAGE = '......StaticRootS3BotoStorage' S3_URL = '//%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME MEDIA_URL = S_3 URL + 'media/' MEDIA_ROOT = MEDIA_URL STATIC_URL = S3_URL + 'static/' ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/' example model field: def get_upload_path(instance, filename): dirname = instance.__class__.__name__ return os.path.join("images", dirname, str(instance), filename) image = models.ImageField(upload_to=get_upload_path, storage=OverwriteStorage(), blank=True, null=True) -
How to send a body in Swagger Django documentation?
I am trying to use the Swagger documentation in my Django project. However, I am not able to send the body. Furthermore, the List Operations doesn't work. Does Anyone has an idea how to fix it? I only have the default settings: urls.py: from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title='Title API') urlpatterns = [ url(r'^swagger', schema_view), ] I can only list all of my URLs and log in as admin. Logout doesn't work. At this moment when I choose Expand Operations, I see something like this: -
Django model error: ProgrammingError: permission denied for relation gallery_image
I made a mistake and overwrote the Django server's settings file with the local version and I lost the database settings for postgresql I have setup a new user and when I tried to reload the site again I get an error from one of the models as permission denied for relation gallery_image if I try this command from the shell from gallery.models import Image I get back ProgrammingError: permission denied for relation gallery_image -
Deploy Django project on google Cloud App Engine with external libraries
Good day! I need to deploy an app on Python Django with following libs: certifi==2017.4.17 chardet==3.0.4 Django==1.11.2 httplib2==0.10.3 idna==2.5 oauth2==1.9.0.post1 psycopg2==2.7.1 pytz==2017.2 requests==2.18.1 urllib3==1.21.1 And I have to connect it to PostgreSQL database. So, what environment shall I use? Standart or Flexible? And how shall I install those libraries to the environment? P.S. I've tried everything: app.yaml, appengine_config.py, I has installed libs directly to source ('libs' folder), and adding libs to app.yaml, and even google.appengine.ext.ndb.django_middleware.NdbDjangoMiddleware In the end I have: ImproperlyConfigured: Error loading psycopg2 module: dynamic module does not define init function (init_psycopg) -
Django channels Group send stop working
I am working on ordering system and using django-channels for sending a notification to an admin about the order has been placed and it works only with 1-2 orders perfectly after that no notification. consumers.py from channels import Group from channels.sessions import channel_session @channel_session def ws_connect(message): print "Connect" message.reply_channel.send({"accept": True}) Group('admin-channel', channel_layer=message.channel_layer).add(message.reply_channel) @channel_session def ws_disconnect(message): print "Disconnect" Group('admin-channel', channel_layer=message.channel_layer).discard(message.reply_channel) views.py def view(request): # some order realted processing message = { "status": "Success", "order-id": order.id } Group('admin-channel').send({ "text": json.dumps(message) }) chat.js $(function () { // When we're using HTTPS, use WSS too. var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws"; var chatsock = new ReconnectingWebSocket(ws_scheme + '://' + window.location.host + "/order"); chatsock.onmessage = function (message) { var data = JSON.parse(message.data); console.log(data); }; }); -
There is a way to check if a model field contains a substring?
I wanted to know if I can do things like this: full_string = "12345" substring = "123" Model.objects.filter.contains(field = substring) More or less like this. In summary I want to search for a substring, not the string itself. -
How do I make a button unavtice on radio button click?
I want to make a submit button unactive (not clickable) until one of form's radio buttons is checked. This is what I have so far: {% for answer in form.poll.answers.all %} <p class='field radio question'> <input id='{{ form.answer.auto_id }}_{{ answer.pk }}' type='radio' name='{{ form.answer.html_name }}' value='{{ answer.pk }}' /> <label for='{{ form.answer.auto_id }}_{{ answer.pk }}'> <em>{{ answer }}</em> </label> </p> {% endfor %} <button class='buttons' type='submit' id='id_vote_button'>{% trans "Vote" %}</button> <script src='{% static 'scripts/libs/jquery.js' %}'></script> <script> $("input.radio").on('click', function () { console.log("click test"); if ($('form.poll input.radio:checked')[0]) { console.log("true test"); $("#id_vote_button").setAttribute('active', true); } else { console.log("false test"); $("#id_vote_button").setAttribute('active', false); } }); </script> The problem is the $("input.radio").on('click', function () does not cause any effect in console when I click on radio buttons. -
PyCharm: debugging Django shell in a standard terminal window
I am using PyCharm to debug django code in the shell as suggested in this post. However, I miss being able to use ctrl+r and vertical arrows to quickly recall previous commands like one can do when running manage.py shell in standard terminal (for me, it's Gnome Terminal on Ubuntu). Is there a way to attach the PyCharm debugger to a manage.py shell session running in a standard terminal window? -
Error was: cannot import name BaseDatabaseOperations
I am making an application using mongodb and django.i cant find any other way to connect my database with django.So use mongokit for connection And i getting this error :- command prompt- python manage.py runserver Traceback (most recent call last): File "manage.py", line 11, in <module> execute_from_command_line(sys.argv) File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 312, in execute django.setup() File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/somya/Desktop/backup/admin_python/admin_app/models.py", line 24, in <module> from django_mongokit import connection File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django_mongokit/__init__.py", line 3, in <module> from shortcut import get_database, get_version, connection File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django_mongokit/shortcut.py", line 13, in <module> connection = connections['mongodb'].connection File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/db/utils.py", line 240, in __getitem__ backend = load_backend(db['ENGINE']) File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/db/utils.py", line 129, in load_backend raise ImproperlyConfigured(error_msg) django.core.exceptions.ImproperlyConfigured: 'django_mongokit.mongodb' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: u'base', u'mysql', u'oracle', u'postgresql_psycopg2', u'sqlite3' Error was: cannot import name BaseDatabaseOperations -
How to connect hashtags to posts for a HashTag cloud in Django
The HashTags that are made in new posts get connected to every other post in the database. I need them to connect only to posts that have the same hashtags to implement a hashtag cloud after. Something goes wrong, when i add a new post and make a new tag or even update an old tag, if i go to the admin section and check, the tag's are connected to all the posts in the database. What am I doing wrong. Got stuck with this for a while. Here is my code: My models.py from django.db import models # Create your models here. from user_profile.models import User class Post(models.Model): # postad_category = models.ForeignKey(Category) # postad_name = models.CharField(max_length=250) user = models.ForeignKey(User) text = models.CharField(max_length=300) created_date = models.DateTimeField(auto_now=True) country = models.CharField(max_length=30, default="Global") # postad_logo = models.CharField(max_length=1000) is_active = models.BooleanField(default=True) is_favorite = models.BooleanField(default=False) def __str__(self): return self.name class HashTag(models.Model): """HashTag model""" name = models.CharField(max_length=64, unique=True) post = models.ManyToManyField(Post) def __str__(self): return self.name My views.py class PostPost(View): """Post - post form available on page /user/<username> URL""" def post(self, request, username): form = PostForm(self.request.POST) if form.is_valid(): # post = form.save(commit = False) # post.user = request.user user = User.objects.get(username=username) post = Post(text=form.cleaned_data['text'], user=user, # country=form.cleaned_data['country'] … -
Find index of an object in array for Internet Explorer
I have associated array Like - $scope.list = [ {prop1:"abc",prop2:"qwe"},strong text {prop1:"bnmb",prop2:"yutu"}, {prop1:"zxvz",prop2:"qwrq"} ]; and want to find the Index of object I am using $scope.value = 'abc'; var index = $scope.list.findIndex(x => x.prop1 == $scope.value); This is working for all browsers but not working in Internet Explorer. Can any body help me ?