Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python manage.py & Mysql all of a sudden don't work (Python manage.py run fine before without Mysql)
All of a sudden, after trying, to integrate React into Django following this tutorial manage.py Django stopped working. Every time I try to run the server or even try to find out the possible commands with python manage.py I get the following error: (Python manage.py run fine before without Mysqldb) Traceback (most recent call last): File "C:\Users\Brian\GOOGLE~1\Carmine\programs\Python\Django\RYASE_~1\lib\site-packages\django\db\backends\mysql\base.py", line 25, in <module> import MySQLdb as Database ImportError: No module named 'MySQLdb' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\Brian\GOOGLE~1\Carmine\programs\Python\Django\RYASE_~1\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Users\Brian\GOOGLE~1\Carmine\programs\Python\Django\RYASE_~1\lib\site-packages\django\core\management\__init__.py", line 341, in execute django.setup() File "C:\Users\Brian\GOOGLE~1\Carmine\programs\Python\Django\RYASE_~1\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Brian\GOOGLE~1\Carmine\programs\Python\Django\RYASE_~1\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models(all_models) File "C:\Users\Brian\GOOGLE~1\Carmine\programs\Python\Django\RYASE_~1\lib\site-packages\django\apps\config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "C:\Users\Brian\GOOGLE~1\Carmine\programs\Python\Django\RYASE_~1\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 662, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "C:\Users\Brian\Google Drive\Carmine\programs\Python\Django\Ryase_virtual_env\RayseV\authentication\models.py", line 7, in <module> from django.contrib.auth.models import ( File "C:\Users\Brian\GOOGLE~1\Carmine\programs\Python\Django\RYASE_~1\lib\site-packages\django\contrib\auth\models.py", line 4, in <module> from django.contrib.auth.base_user import … -
How to check for an erroneous primary key parameter in a filtered django ORM query?
Let's say I'm given a list of primary keys of model instances on which I'm to perform an operation (eg delete()). I could do: Widgets.objects.filter(pk__in=keys).delete() However, then I wouldn't know if there were erroneous pks in keys that wouldn't have been caught by the filter. What's the most efficient way to check that all the pks are legitimate before performing the operation? len(keys) == Widgets.objects.filter(pk__in=keys).count()? -
Access values of table using foreign key, in django
I have 3 tables in my database. 1. users 2. sessiontokens 3. post I have used foreign key to refer to user table in both sessiontoken and post. I want to check in accesstoken table if a query exists and get corresponding user_id value from it. models class User(models.Model): email = models.EmailField() name = models.CharField(max_length=30) username = models.CharField(max_length=20) password = models.CharField(max_length=100) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) class SessionToken(models.Model): user = models.ForeignKey(User) session_token = models.CharField(max_length=255) created_on = models.DateTimeField(auto_now_add=True) is_valid = models.BooleanField(default=True) def create_token(self): self.session_token = uuid.uuid4() class Post(models.Model): user = models.ForeignKey(User) image = models.FileField(upload_to='user_images') caption = models.CharField(max_length=240) image_url = models.CharField(max_length=255) created_on = models.DateTimeField(auto_now_add=True) Here is what happens, a session_token is generated everytime a user logs in. and we check if the user is logged in right now or not using the following function. def check_validation(request): if request.COOKIES.get('session_token'): session = SessionToken.objects.filter(session_token=request.COOKIES.get('session_token')) if session: return session else: return None I want to set user_id in post table from matching the user_id in sessiontoken from above function def upload_view(request): usr = check_validation(request) if usr: if request.method == "GET": form = PostForm() return render(request, 'upload.html', {'form': form}) elif request.method == "POST": form = PostForm(request.POST, request.FILES) if form.is_valid(): pic = form.cleaned_data.get('image') title = form.cleaned_data.get('caption') post … -
How to dynamically generate html list from json array received via ajax call?
I am a Django novice attempting to build an app that allows users to add tracks to a playlist. I use sessions to generate a list of track id strings in a view and return an http response with the serialized array. The problem is that trying to iterate through the array in the template to build an ordered list does not format properly. It displays as a python list instead of the expected bulleted html list. Any help would be greatly appreciated! the Div <!DOCTYPE html> <div id="playlist"> <ol> {% for track in playlist %} <li>{{track}}</li> {% endfor %} </ol> </div> </html> the javascript <script type="text/javascript"> $(document).on('submit', '.track_form', function() { var $form = $(this); $.ajax({ url: $form.attr('action'), data: $form.serialize(), type: $form.attr('method'), success: function (data) { $("#playlist").html(data); }, error: function(data) { console.log('There was a problem'); } }); return false; }); </script> the view def artistpage(request): if request.method == 'POST': session_playlist = request.session.get('session_playlist', []) tname = str(request.POST.get('track_name')) session_playlist.append(tname) request.session['session_playlist'] = session_playlist return HttpResponse(json.dumps(session_playlist)) -
Django - How to
In Django, I want to filter data based on the selection made by the user from frontend drop down list. How can I make the return value within a function to be available outside the function? I'm using Django Rest Framework but I think same is true for Django in any case. Here is my views.py class ListAirlineYearFinancialData(generics.ListAPIView): # Serialized data serializer_class = FinancialDataSerializer def airline_dashboard(request): airline_list = Airline.objects.all() year_list = Year.objects.all() if request.method == 'GET': identifier = request.GET.get('id', None) if identifier: airline_id = Airline.objects.filter(pk=identifier) return airline_id # How to reference this return value outside function to queryset below? return render(request, 'dashboard/company_page.html', {'airline_list': airline_list, 'year_list': year_list}) queryset = FinancialData.objects.filter(airline_id=airline_id) # I get error airline_id is not defined queryset_filtered = queryset.filter(financial_year_id=1) def get_queryset(self, *args, **kwargs): return self.queryset_filtered Django is giving me an error that airline_id is not defined in queryset. How can I reference the value defined inside the function to be available outside and use that to filter data? -
sorl-thumbnail not displaying image
I have got sorl in my settings file INSTALLED_APPS = ( 'account', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social.apps.django_app.default', 'images', 'sorl.thumbnail', here is my html {% load thumbnail %} {% block title %}{{ user.username }}{% endblock %} {% block content %} <div id="details"> {% thumbnail image.image "551" as im %} <a href="{{ image.image.url }}"> <img src="{{ im.url }}" alt="{{ image.title }}"class="image-detail"> </a> {% endthumbnail %} when i Take out the thumbnail tag, <img src="{{ image.image.url }}">, an image displays with no problems. I was not having this problem while on development stage. but now Im about to deploy and this is happening. there is no img element to inspect also. Any idea what could have gone wrong?? here is my media url and root.(just incase) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') -
Django or Flask or possibly none!, for an API based Website for object detection in images?
as a self learned programmer who is fairly familiar with python, I'm trying to develop a website which has an API for object detection in an image, i was wondering should I use Django or Flask or they are a bit overkill for this task, what do you suggest for front end development, can i do it also in these frameworks. I'm trying to keep whole project in python as far as possible. so what so you guys think, any suggestions? -
Form not returning certain file types correctly (doc, docx, ppt, pptx)
I am writing a Django form validation for file types. The supported file types are pdf, doc, docx, ppt and pptx. I am using python-magic utilizing libmagic python library to check the MIME types. I have created a method in helpers.py validate_user_file_upload(upload) that that the forms.py clean_file method initiates and return whether not the file type is supported. It seems to work good, but only for pdf files. It does not work for the other file types specified, it will just return the error message in validate_user_file_upload(upload). I have also checked the python console to see if it is getting the file types for doc, docx, ppt and pptx correctly, and it does. So python-magic is doing its job thus validate_user_file_upload(upload) is doing its job. I have figured out that it is the clean_file method that is causing the problem. The clean_file is actually returning file when the file type is supported however for some reason, it defaults back to the error message when it is not a pdf. I also checked in the console to see whenever the file type is correct and it goes to the error message, and discovered the error message condition was not executed. So … -
How to add custom class in wagtail richtextfiled
how can i add button which adds class in hallo.js editor? Here is my code, but it dont works, it ony register fuction in wagtai;s edit interface. In the end I need to add any class to selection or current tag. Mb I can see it in html in someway and add classes manually? (function() { (function(jQuery) { return jQuery.widget('IKS.center', { options: { editable: null, toolbar: null, uuid: '', buttonCssClass: 'center' }, populateToolbar: function(toolbar) { var buttonElement, buttonset; buttonset = jQuery('<span class="' + this.widgetName + '"></span>'); buttonElement = jQuery('<span></span>'); buttonElement.hallobutton({ uuid: this.options.uuid, editable: this.options.editable, label: 'Center element', command: 'addClass("center")', icon: 'icon-horizontalrule', cssClass: this.options.buttonCssClass }); buttonset.append(buttonElement); buttonset.hallobuttonset(); return toolbar.append(buttonset); } }); })(jQuery); }).call(this); -
Django Supervisor FATAl Exited too quickly (process log may have details)
I am using supervisor in laravel some time my supervisor work fine and some time got error. FATAl Exited too quickly (process log may have details). This is my supervisor file. [program:chart_app] command = /webapps/chart_app/bin/gunicorn_start user = chart stdout_logfile = /webapps/chart_app/logs/gunicorn_supervisor.log redirect_stderr = true environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8 error in logs > supervisor: couldn't exec /webapps/chart_app/bin/gunicorn_start: > ENOEXEC supervisor: child process was not spawned supervisor: couldn't > exec /webapps/chart_app/bin/gunicorn_start: ENOEXEC supervisor: child > process was not spawned supervisor: couldn't exec > /webapps/chart_app/bin/gunicorn_start: ENOEXEC supervisor: child > process was not spawned supervisor: couldn't exec > /webapps/chart_app/bin/gunicorn_start: ENOEXEC supervisor: child > process was not spawned supervisor: couldn't exec > /webapps/chart_app/bin/gunicorn_start: ENOEXEC supervisor: child > process was not spawned supervisor: couldn't exec > /webapps/chart_app/bin/gunicorn_start: ENOEXEC supervisor: child > process was not spawned supervisor: couldn't exec > /webapps/chart_app/bin/gunicorn_start: ENOEXEC supervisor: child > process was not spawned supervisor: couldn't exec > /webapps/chart_app/bin/gunicorn_start: ENOEXEC supervisor: child > process was not spawned -
Django MultiValueDictKeyError for posting values
I never had this kind of error before. I have a form in my template : <form method="POST" action="" style="display: inline;"> {% csrf_token %} <input type="hidden" value="{{answer.id}}" name="current_comment" /> <input type="hidden" value="{{post.author.id}}" name="author_id" /> <input type="hidden" value="{{post.id}}" name="article_id" /> <button name="down" id="down{{answer.id}}" type="submit" class="w3-button w3-margin-bottom" style="display: inline; background:url({{media}}media/images/dislike.png) no-repeat; background-position: center; border:none; width: 25px; height: 25px; background-size: 16px 16px;"> </button>{%for count in up%}{%if answer.id in count%}{{count.1}}{%endif%}{%endfor%} </form> And I want to get the datas from my view : article = request.POST.get('article_id') author = request.POST.get('author_id') comment = request.POST.get('current_comment') I also tried : article = request.POST['article_id'] author = request.POST['author_id'] comment = request.POST['current_comment'] But for an unkown reason, there is only request.POST['current_comment'] and comment = request.POST.get('current_comment') which return a value. For the other, I get the value None or a MultiValueDictKeyError following the method POST[] or POST.get(). -
How to keep track of particular user's history in any application using python?
I want to develop a website which keeps track of user's activity and save that activity to suggest useful information to the user.I want to know whether which tools or libraries I should use to achieve such task. I am looking forward to using Python and Django for the project. Please suggest me which library or tool I should research in order to implement it. It would be a great help.Thanks for your time :) -
Django - right way to have multiple tcp sockets running
Im working on an Web GUI for industrial equipments (linux systems). The industrial equipment can comunicate via TCP sockets to send measurements and parameters. So far we have a web server running Django and Postgres. The client (user) communicates with django via Websockets (django channels). I would like to know which is the best way to have the tcp sockets running in django? Should I use multithreading? Will it scale this way, if the server should run in more computers. -
Django - 'Feed' object is not callable
I'm trying to add this form to my project and i get this error: 'Feed' object is not callable When I was using only models.py it was working. Here is my code: forms.py from django import forms from .models import Feed class FeedForm(forms.ModelForm): class Meta: model = Feed() fields = [ 'post' ] models.py from django.db import models class Feed(models.Model): user = models.ForeignKey('auth.User') date = models.DateTimeField(auto_now_add=True) post = models.TextField(max_length=255) def __str__(self): return self.post views.py def post_new(request): if request.method == "POST": form = FeedForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.date = timezone.now() post.save() else: form = FeedForm() return render(request, 'feeds/feed_edit.html', {'form': form}) Thanks for help. -
Django one to many send to rest-api
I try to create method in django model,that returns info about other object by rest-api. models.py class Stream(models.Model): master = models.ForeignKey('Master', null=True, default=None) class Master(models.Model): first_name = models.CharField(max_length=255) def get_performers(self): streams = Stream.objects.filter(master=self) catalogs = Catalog.objects.filter(stream__in=streams).order_by('-datetime')[:10] catalogs = reversed(catalogs) performers = catalogs.performers return performers class Catalog(models.Model): performer = models.ForeignKey('Performer', blank=True) class Performer(models.Model): name = models.CharField(max_length=255) How can I send objects performer in every catalogs(set of objects)? -
Start Django project by one clik using BAT file
I want the user press one icon (link to BAT file) on the DESKTOP and it starts two processes. first - start django server second - crome file.bat @ECHO OFF start cmd.exe "D: && cd D:\D1\ && python manage.py runserver" start C:\"Program Files (x86)"\Google\Chrome\Application\chrome.exe "http://127.0.0.1:8000/" where is my mistake? BAT file just start cmd.exe and go to directory D:\D1 and nothing more. The sintax of the second line is correct. Where is the error? -
Block User-Agent on AWS Elastic Beanstalk
I am running a Django application on AWS Elastic Beanstalk. I keep having alerts (for days now) because the following user agent constantly tries to access some pages: "Mozilla/5.0 Jorgee" [30/Jul/2017:13:55:55 +0000] "HEAD /pma/ HTTP/1.1" 403 - "-" "Mozilla/5.0 Jorgee" [30/Jul/2017:13:55:55 +0000] "HEAD /db/ HTTP/1.1" 403 - "-" "Mozilla/5.0 Jorgee" [30/Jul/2017:13:55:56 +0000] "HEAD /admin/ HTTP/1.1" 403 - "-" "Mozilla/5.0 Jorgee" [30/Jul/2017:13:55:56 +0000] "HEAD /mysql/ HTTP/1.1" 403 - "-" "Mozilla/5.0 Jorgee" [30/Jul/2017:13:55:56 +0000] "HEAD /database/ HTTP/1.1" 403 - "-" "Mozilla/5.0 Jorgee" [30/Jul/2017:13:55:57 +0000] "HEAD /db/phpmyadmin/ HTTP/1.1" 403 - "-" "Mozilla/5.0 Jorgee" [30/Jul/2017:13:55:57 +0000] "HEAD /db/phpMyAdmin/ HTTP/1.1" 403 - "-" "Mozilla/5.0 Jorgee" [30/Jul/2017:13:55:57 +0000] "HEAD /sqlmanager/ HTTP/1.1" 403 - "-" "Mozilla/5.0 Jorgee" [30/Jul/2017:13:55:58 +0000] "HEAD /mysqlmanager/ HTTP/1.1" 403 - "-" "Mozilla/5.0 Jorgee" [30/Jul/2017:13:55:58 +0000] "HEAD /php-myadmin/ HTTP/1.1" 403 - "-" "Mozilla/5.0 Jorgee" [30/Jul/2017:13:55:58 +0000] "HEAD /phpmy-admin/ HTTP/1.1" 403 - "-" "Mozilla/5.0 Jorgee" [30/Jul/2017:13:55:59 +0000] "HEAD /mysqladmin/ HTTP/1.1" 403 - "-" "Mozilla/5.0 Jorgee" [30/Jul/2017:13:55:59 +0000] "HEAD /mysql-admin/ HTTP/1.1" 403 - "-" "Mozilla/5.0 Jorgee" [30/Jul/2017:13:55:59 +0000] "HEAD /admin/phpmyadmin/ HTTP/1.1" 403 - "-" "Mozilla/5.0 Jorgee" It used to return 404, but I managed to block it to 403 thanks to the following line in settings.py: DISALLOWED_USER_AGENTS = (re.compile(r'Mozilla\/5.0 Jorgee'), ) Is there a way to … -
How do get custom pagination class working for django rest framework v3.6
I'm trying to implement a custom pagination class on a ViewSet, as per the docs, but the pagination settings are just not doing a single thing. Here's the code for my ViewSet. from rest_framework import status, permissions, viewsets from rest_framework.pagination import PageNumberPagination class ProductViewSetPagination(PageNumberPagination): page_size = 5 page_size_query_param = 'page_size' max_page_size = 1000 class ProductViewSet(viewsets.ModelViewSet): permission_classes = (permissions.IsAuthenticated,) serializer_class = ProductSerializer pagination_class = ProductViewSetPagination # ...etc I even added some defaults to the settings.py file, but I'm still getting all the product instances on a single page on the product-list view. I've tried adding page and page_size query parameters to the URL; this doesn't change anything. 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10, What am I missing? -
select value from jsonfield in queryset
I have the following situation class MyModel(models.Model): my_field = JSONField(null=True, blank=True) my_field is a JSON field with the following structure: { "name": "some name" "id": "some hash id" } I want to perform something like: MyModel.objects.values(my_field__name) which will be equivalent to the postgres query: select my_field->>'name' from my_app_my_model but i can't seem to get django to generate the wanted query. The error im getting is: FieldError: Cannot resolve keyword 'name' into field. Join on 'my_field' not permitted. The main goal here is to provide a list of strings called fields and run the following command: MyModel.objects.values(*fields) so i think that raw sql solutions won't fit here. Custom Lookups are for the WHERE clause and i don't know of any equivalent for the SELECT clause. Any thought on how this can be done? Thanks! -
Django signal simple snippet confusion?
This is a simple Django signal snippet I found on the internet to generate a profile after User creation. What is the need of the second post_save signal. Didn't the first 'create' already save the profile? So why was the second receiver created? @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() -
Django not returning the 'results template' in my Django tutorial
I am using the web-poll app tutorial to understand the Django framework more. In the tutorial after I create the vote method in the my polls/views.py and create the associated polls/templates/index.html, details.html, results.html templates, I am suppose to be presented with a question, 3 options to be selected using radio buttons and the vote button to submit my choice which is found in the details.html template. After I select an option and click the vote button I am to see the number of times I voted for the specific choice in the results.html template. In my polls/views.py file I have the vote method : def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) This is to ensure that when I vote I see the metrics and if I click the vote button without selecting a radio button then I will see … -
django rest framework serializer save() "got key error message"
I'm trying to use the save method on my custom django rest framework serializer. I have a create method in the serializer and my views.py looks like this (simplified): def some_method(): validated_data = { 'id': some_integer_id, 'created_at': "some text"} context_data = { 'user': request.user.id} obj_serialized = MyCustomSerilizer(data=validated_data, context=context_data) if message_serialized.is_valid(): try: message_serialized.save() return Response(message_serialized.data) except BaseException as e: raise APIException(detail=e.message) else: raise ValidationError(message_serialized.errors) this returns an exception: Got KeyError when attempting to get a value for field `created_at` on serializer `RoomMessageSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `dict` instance. Original exception text was: u'created_at'. here is my serilizer: class MyCustomSerializer(serializers.Serializer): id = serializers.IntegerField() message = PersianCharField() created_at = serializers.CharField() def create(self, validated_data): print validated_data['created_at'] user = self.context.get('user') return {'id': validated_data['id'], 'message': validated_data['message']} the first line of create method prints the value of created_at field correctly. the data I send with the dict is unicode and so the keys for the dict turn unicode too but I doubt that's the case since I can print the validated_data['created_at']. thanks in advance. -
Python getting information from two models in django
I am trying to access information from two models in my django application here is my models: class Events(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=50, blank=True, default='') description = models.CharField(max_length=500, blank=True, default='') date = models.CharField(max_length=200, blank=True, null=True) time = models.CharField(max_length=200, blank=True, null=True) price = models.CharField(max_length=240, blank=True, default='') active = models.CharField(max_length=1, blank=True, default='d') seats = models.CharField(max_length=200, blank=True, default='') alcohol_choice = models.CharField(max_length=1, blank=True, default='n') starter = models.CharField(max_length=350, blank=True, default='') main_menu = models.CharField(max_length=350, blank=True, default='') dessert = models.CharField(max_length=350, blank=True, default='') notes = models.CharField(max_length=350, blank=True, default='') class Meta: app_label = 'events' class GalleryImagesEvents(models.Model): event = models.ForeignKey(Events, on_delete=models.CASCADE) file = ResizedImageField(size=[1200, 800], quality=75, upload_to="events/static/galleryimages") file_thumbnail = ResizedImageField(size=[300, 300], crop=['middle', 'center'], upload_to="events/static/galleryimages/thumbnails") order = models.TextField(default='', blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) class Meta: ordering = ['order'] I can have multiple Events for an user, Each event can have multiple gallery images. What I am trying to do is get all the events from the user and only get one image for the event from the galleryimagesevent model attached to the event. @csrf_exempt @login_required(login_url="/login/") def EventsView(request): user = User.objects.get(pk=request.user.id) events_list_data = Events.objects.filter(user_id=user).order_by('-date')[:10] events_list_images = GalleryImagesEvents.objects.filter(event_id=events_list_data) return render(request, 'events/view.html', {"events_list_data":events_list_data, 'events_list_images': events_list_images}) I know classes are used etc But I am still … -
django get all changed and unchanged forms from formset while updating
while i am editing formset it only iterate through the changed and new added forms but i want to iterate through all the forms. How can i do that . Somebody please help me views.py for form in dynamic_price_formset_instance: unit_price = form.unit_price # if not form.has_changed(): i tried this but not working # unit_price = form.unit_price price_list.append(unit_price) form.save() default_dynamic_price = min(price_list, default=0.00) here i want to get unit_price of all the products . but here i am able to get only changed or newly added forms unit price. -
AttributeError: 'Apps' object has no attribute 'cache'
I have installed Django 1.10. I need to import the loafing but not able to import it. I am trying to connect my django app with elasticsearch using Haystack and wanted to build index. The code I want to run is python manage.py rebuild_index The error I get is: base ---dir /Manish/Projects/Spark/ad-tracking-django-env/ad-tracking-django Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/django/apps/config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/catalog/models.py", line 79, in <module> for model_cls in connected_models(): File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/catalog/utils.py", line 19, in connected_models yield apps.cache.get_model(*model_str.split('.')) AttributeError: 'Apps' object has no attribute 'cache' The main error is: AttributeError: 'Apps' object has no attribute 'cache'