Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Multiple choice models with integer value
class Feedback(models.Model): #choices NEGATIVE = '-1' NEUTRAL = '0' POSITIVE = '1' FEEDBACK_TYPE_CHOICES = ( (NEGATIVE, 'Negative feedback'), (NEUTRAL, 'Neutral feedback'), (POSITIVE, 'Postive feedback'), ) #database fields short_description = models.CharField('Short opinion: ' ,max_length=100, default='SOME STRING') text = models.TextField('Detailed opinion: ', max_length=300, default='SOME STRING') feedback = models.CharField('Feedback choice: ', max_length=3, choices=FEEDBACK_TYPE_CHOICES, default = 1) pub_date = models.DateTimeField('date published') def feedback_for_user(self): return 1 #def reputation(self): # return ((self.positivefeedback-self.negativefeedback)/(self.positivefeedback+self.neutralfeedback+self.negativefeedback))*100 class User(models.Model): username = models.CharField(max_length=50) password = models.CharField(max_length=50) email = models.EmailField(max_length=100) eddies = models.IntegerField() premium = models.BooleanField() feedback = models.ForeignKey(Feedback, on_delete=models.CASCADE) def __str__(self): return self.username I'm trying to archive model OneToMany, where 1 User can have multiple feedbacks. How can I archive a function that could calculate the feedback outcome score of a specific user? -
Having trouble with exempt url
Hi I am trying to exempt a url in my project so that the user can bypass the middleware and reset their password without being logged in. However the urls I have placed in LOGIN_EXEMPT_URLS don't seem to fix this, instead the link to reset-password redirects the user to account/login. settings.py: LOGIN_EXEMPT_URLS = { r'^account/logout/$', r'^account/register/$', r'^account/reset-password$', r'^account/reset-password/done/$', r'^account/reset-password/confirm(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,23})/$', r'^account/reset-password/complete/$', } middleware.py: url_is_exempt = any(url.match(path)for url in EXEMPT_URLS) if path == reverse('accounts:logout').lstrip('/'): logout(request) if request.user.is_authenticated and url_is_exempt: return redirect(settings.LOGIN_REDIRECT_URL) elif request.user.is_authenticated or url_is_exempt: return None else: return redirect(settings.LOGIN_URL) html: This is in {% else %} (user.is.authenticated) <ul class="navbar-nav ml-auto"> <li class='nav-item'> <a class="nav-link" href='{% url 'accounts:reset_password' %}'>Forgotten Password?</a> Everything in html is properly formatted but I think some of the code is bugging out. Sorry about that So whats the problem? thnx -
Django- Getting string value instead of integer even when integer value in passed through `raise exceptions.ParseError`
I want 0 or 1 in status through raise exceptions.ParseError({'data':{},'message':'Email address already exists',"status":0}) but I am getting a string value -
Evaluate whole django queryset in one database hit
I'm looking for a way to evaluate a whole django queryset in one database hit. I'm using Django 2.0.8 with Python 3.6.5. I used to evaluate querysets listing them: queryset = Model.objects.all() list(queryset) which only performed one database hit. But now, it looks like this is hitting the database n times -n being the length of the queryset- which is a problem when n is large and the database hits costly. Thanks -
Django 1.11 Direct assignment to the forward side of a many-to-many set is prohibited
I have one model UserSong which has two m2m fields with models Genre and Language class UserSong(models.Model): title = models.CharField(max_length=100) song_file = models.FileField(upload_to=user_song_directory_path, validators=[validate_audio_file_extension]) genre = models.ManyToManyField(Genre) language = models.ManyToManyField(Language) Genre class is class Genre(models.Model): name = models.CharField(max_length=255) created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) status = models.BooleanField(default=False) Language class is class Language(models.Model): name = models.CharField(max_length=255) created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) status = models.BooleanField(default=False) I am trying to add m2m fields in UserSong object as genre_name_list = Genre.objects.filter(name__in=self.cleaned_data['genre'].values_list('name',flat=True)) # instance.genre.add(*genre_name_list) instance.genre.set(genre_name_list) language_name_list = Language.objects.filter(name__in=self.cleaned_data['language'].values_list('name',flat=True)) # instance.language.add(*language_name_list) instance.language.set(language_name_list) The problem here lies is , m2m table is getting updated as it should but still Django is giving me error Direct assignment to the forward side of a many-to-many set is prohibited. Use language.set() instead. -
Django - run requests in bulk
we're using django 1.10, python 3.5 We have views for different models, let's say 'Item' for example. The Item view has it's own permission_classes, serializers, signal etc. and it allows creation and update. for example (part of it): class ItemViewSet(mixins.CreateModelMixin, mixins.UpdateModelMixin): permission_classes = [UserPermissions, ItemViewPermissions] serializer_class = ItemSerializer filter_backends = (ItemFilter, OrderingFilter,) Now lets say I want to allow bulk operations (bulk update) meaning update several items in one request from client - Should I actually make request for each item (in order to use the request benefits such as signals, permissions etc)? and if so - how should I do it? which functions? using 'requests' library or something like 'test.client.patch' which we use in tests? Or there is other way to faster update the items and still make use of the Request benefits? -
Auto save in 5 sec interval using jQuery in Django
<script> $(document).ready(function() { $("form").submit(function(){ alert("submitted"); }); }); </script> How to change the code so that i can autosave the entered information in 5 sec or above. For example in Django I have these fields: class Article(models.Model): published_by = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=250, unique=True) subtitle = models.CharField(max_length=250, blank=True) writer = models.CharField(max_length=250, blank=True) context = models.CharField(max_length=250, blank=True) So the condition should be if either something is written in title or text it should autosave in 5 second. -
Avoid n+1 queries for many-to-many relation to self via other many-to-many relation
I have a model of a PolygonMap, consisting of a number of PolygonTiles. Each PolygonTile has a center point and a number of CornerPoints spanned by Edges. Hence each Edge has two CornerPoints and two PolygonTiles. This is implemented via two many-to-many relationships on the model Edge as presented below and works fine (using PostgreSQL for distinct() with argument field). class PolygonMap(models.Model): pass class PolygonTile(models.Model): location = PointField() polygon_map = models.ForeignKey(PolygonMap, on_delete=models.CASCADE def adjacent(self): return PolygonTile.objects.filter(edges__polygon_tiles=self).exclude(id=self.id) def corner_points(self): return CornerPoint.objects.filter(protruded_edges__polygon_tiles=self).distinct('id') class CornerPoint(models.Model): location = PointField() polygon_map = models.ForeignKey(PolygonMap, on_delete=models.CASCADE # ... functions like the ones in PolygonTiles class Edge(self): polygon_tiles = models.ManyToManyField(PolygonTile, related_name='edges') corner_points = models.ManyToManyField(CornerPoint, related_name='protruded_edges') For each PolygonTile in a PolygonMap I now want to fetch all adjacent PolygonTiles (and later on CornerPoints). This I can do using polygon_tiles = PolygonMap.objects.first().polygontile_set().all() adjacent = [p.adjacent() for p in polygon_tiles] As you can imagine this ends up N+1 queries for the adjacent PolygonTiles. So my question is, how do I fix this? I've tried to use combinations of prefetch_related with and without Prefetchobjects, custom managers and rewriting the adjacency query but I can't seem to get it to work. -
Django and Jbrowse
Did you tried to integrate jBrowse (https://jbrowse.org/) into a django web application? if so, can you please describe how you did it? thanks a lot for your help -
How to perform pagination for context object in django?
I have tried something like this in views.py: class HomePage(TemplateView): template_name = "clouderp/index.html" def get_context_data(self, **kwargs): context = super(HomePage, self).get_context_data(**kwargs) qs = Blog.objects.all() context['blog_list'] = qs page = self.request.GET.get('page') paginator = Paginator(qs, 4) try: users = paginator.page(page) except PageNotAnInteger: users = paginator.page(1) except EmptyPage: users = paginator.page(paginator.num_pages) context['users'] = users return context And in template: {% if users.has_other_pages %} <ul class="pagination"> {% if users.has_previous %} <li><a href="?page={{ users.previous_page_number }}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} {% for i in users.paginator.page_range %} {% if users.number == i %} <li class="active"><span>{{ i }} <span class="sr-only"></span></span></li> {% else %} <li><a href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if users.has_next %} <li><a href="?page={{ users.next_page_number }}">&raquo;</a></li> {% else %} <li class="disabled"><span>&raquo;</span></li> {% endif %} </ul> {% endif %} I have created a blog application using django I want to show all my blogs in my main index.html page and also wanted to do pagination for the blogs in my index page...I was wondering how to do it...Because the process I have done the blogs are not paginated according to 4 at a time... -
Django not able to create object in python
I'm trying to create json but not able to create proper.my response is not similar that i want . please help to make it solve. views.py json={} all_results=[] restaurants={} for i in restaurant: restaurant=Restaurant.objects.get(id=i.id) reviews=Review.objects.filter(restaurant_id=i.id).count() # review_serializer=ReviewSerializer(reviews,many=True) restaurant_serializer=RestaurantSerializers(restaurant) json['distace'] = i.distance json['review_count']=reviews json['liked']=False restaurants['nearby_restaurants']=json restaurants['popular_restaurants']=json all_results.append(restaurants) return all_results response: that i'm getting [ { "top_reviewed_restaurants": { "distace": 1.53590595706412, "review_count": 0, "liked": false }, "nearby_restaurants": { "distace": 1.53590595706412, "review_count": 0, "liked": false } } ] Response: that i want { "nearby_restaurants": [ { "restaurant_id": 1, "name": "", "primary_image_url": "", "is_liked_by_user": true, "address": "",`enter code here` "rating": 1, "reviews_count": 200 } ], "popular_restaurants": [ { "restaurant_id": 1, "name": "", "primary_image_url": "", "is_liked_by_user": true, "address": "", "rating": 1, "reviews_count": 200 } ] } I'm trying to create json but not able to create proper.my response is not similar that i want . please help to make it solve. -
Django rest framework AttributeError: 'function' object has no attribute 'get_extra_actions'
here is the errors: Unhandled exception in thread started by <function wrapper at 0x7ff9fc5b6848> Traceback (most recent call last): File "/home/wishbook/Desktop/Dev/rest/env/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/home/wishbook/Desktop/Dev/rest/env/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "/home/wishbook/Desktop/Dev/rest/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/home/wishbook/Desktop/Dev/rest/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/home/wishbook/Desktop/Dev/rest/env/local/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/home/wishbook/Desktop/Dev/rest/env/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/home/wishbook/Desktop/Dev/rest/env/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/home/wishbook/Desktop/Dev/rest/env/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 256, in check for pattern in self.url_patterns: File "/home/wishbook/Desktop/Dev/rest/env/local/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/wishbook/Desktop/Dev/rest/env/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 407, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/wishbook/Desktop/Dev/rest/env/local/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/wishbook/Desktop/Dev/rest/env/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 400, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/wishbook/Desktop/Dev/rest/settings/urls.py", line 16, in <module> url(r'', include(router.urls)), File "/home/wishbook/Desktop/Dev/rest/env/local/lib/python2.7/site-packages/rest_framework/routers.py", line 101, in urls self._urls = self.get_urls() File "/home/wishbook/Desktop/Dev/rest/env/local/lib/python2.7/site-packages/rest_framework/routers.py", line 363, in get_urls urls = super(DefaultRouter, self).get_urls() File "/home/wishbook/Desktop/Dev/rest/env/local/lib/python2.7/site-packages/rest_framework/routers.py", line 261, in get_urls routes = self.get_routes(viewset) File "/home/wishbook/Desktop/Dev/rest/env/local/lib/python2.7/site-packages/rest_framework/routers.py", line 176, in get_routes extra_actions = viewset.get_extra_actions() AttributeError: 'function' object has no attribute 'get_extra_actions' here is my views.py from rest_framework.decorators import api_view @api_view(['GET', 'POST']) def CatalogView(request): if request.method == 'GET': … -
When I try to make migrations in django I get an error of undefined DJANGO_SETTINGS_MODULE
I made a change to my models.py and then I entered this line to make migrations: django-admin makemigrations and got this error: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I have tried defining the environment variable by export DJANGO_SETTINGS_MODULE=mysite.settings but seems to have no effect. -
In Django-rest-frame work 'NoneType' object has no attribute 'attname'
Here i have using abstract concept but when i try to call product it was throwing Error like 'NoneType' object has no attribute 'attname'. In this models.py Product is the main model and other models like Category, Reviews, Specification and ItemNumber are sub models. In Product all Other sub models are mentioned as array field. I don't know how to over come this so please tell me how to achieve this. Models.py class Categories(models.Model): name = models.CharField(max_length=255) class Meta: abstract = True class CategoriesForm(forms.ModelForm): class Meta: model = Categories fields = ['name'] class Specifications(models.Model): cost_price = models.FloatField() quantity = models.IntegerField() sell_price = models.FloatField() size = models.CharField(max_length=255) class Meta: abstract = True class SpecificationsForm(forms.ModelForm): class Meta: model = Specifications fields = ['cost_price', 'quantity', 'sell_price', 'size'] class Reviews(models.Model): author = models.CharField(max_length=255) date = models.CharField(max_length=255) rating = models.FloatField() comment = models.CharField(max_length=1000) class Meta: abstract = True class ReviewsForm(forms.ModelForm): class Meta: model = Reviews fields = ['author', 'date', 'rating', 'comment'] class ItemNumber(models.Model): spec_id = models.CharField(max_length=20) class Meta: abstract = True class ItemNumberForm(forms.ModelForm): class Meta: model = ItemNumber fields = ['spec_id'] class Product(models.Model): name = models.CharField(max_length=255) image = models.ImageField(upload_to='', blank=True) categories = models.ArrayModelField( model_container=Categories, model_form_class=CategoriesForm ) specifications = models.ArrayModelField( model_container=Specifications, model_form_class=SpecificationsForm ) description = models.TextField() … -
adding custom header language does not reach server
I am on django 1.11 and from front-end, I want to pass a language header. I already am passing Authorization Bearer header parameter successfully but want to add a custom language header as well. Following this, I tried the following in my http interceptor: var lang=localStorage.getItem('lang') || 'en'; //WORKS req = req.clone({ headers: req.headers.set('language',lang) }) //FAILS When I say fails, I meant that the request OPTIONS is sent but it doesn't move on to GET method. My front-end is angular 6 if it matters. Any idea? -
How to pass Django variable into Javascript
I would like to get some help in order to pass Django variable in HTML template into Javascript variable. I believed it will be easy, but up to now I don't overcome to do that. Especially with a Django for loop. I have an HTML piece of code like this : {% for document in publication.documents.all %} <table class="table table-condensed"> <tbody> <tr> <td class="col-md-1"> <canvas id="test{{ document.id }}"></canvas> </td> </tr> </tbody> </table> {% endfor %} Then, I would like to use Javascript code in order to display PDF for each document. So, I have something like this with JS : <script src="https://mozilla.github.io/pdf.js/build/pdf.js"></script> <script type="text/javascript"> var document_upload = "{{ document.upload }}"; //Django variable pdfjsLib.getDocument('http://localhost:8000/media/'+document_upload).then(function (pdf) { console.log("pdf loaded"); pdf.getPage(1).then(function (page) { var scale = 0.30; var viewport = page.getViewport(scale); var canvases = document.getElementsByTagName('canvas'); Array.from(canvases).forEach((canvas) => { var context = canvas.getContext('2d'); canvas.height = viewport.height; canvas.width = viewport.width; var renderContext = { canvasContext: context, viewport: viewport }; page.render(renderContext); }); }); }); </script> But nothing appears in my template. If I make a console.log() for these : var document_upload = "{{ document.upload }}"; //returns blank var document_upload = {{ document.upload }} //returns Undefined Maybe someone could help me ? -
Django ORM Queryset class behave different with same filters
This is a simple question. I want to 2 filters at once with Queryset class. Let me explain. from django.db.models import Q import datetime from .models import Asset query_set = Asset.objects.filter(category__name="car") date_query = {'eav__date__gte': datetime.datetime(2018, 9, 2, 0, 0), 'eav__date__lte': datetime.datetime(2018, 9, 14, 0, 0)} number_query = {'eav__price__gte': '60', 'eav__price__lte': '600'} total_query = {'eav__date__gte': datetime.datetime(2018, 9, 2, 0, 0), 'eav__date__lte': datetime.datetime(2018, 9, 14, 0, 0),'eav__price__gte': '60', 'eav__price__lte': '600'} query_set = query_set.filter(Q(**number_query)) query_set = query_set.filter(Q(**date_query)) in this case, query_set is not empty! query_set = query_set.filter(Q(**total_query)) in this case, query_set is empty! Might someone explain the difference between two query please? Thanks in advance. -
Djangorestframework manytomany update
enter image description here DRF中多对多字段更新 -
Django Group.objects monkey patch problem - 'NoneType' object has no attribute '_meta'
I'm junior dev and I'm trying to monkey patch django.contrib.auth.models Group manager. (Python 2.7.15, Django 1.8) There is my code: class DefaultGroupManager(models.Manager): def get_queryset(self): tests = Test.objects.values() tests_ids = [test['virtual_group_id'] for test in tests] return super(DefaultGroupManager, self).get_queryset().exclude(id__in=tests_ids) Group.objects = DefaultGroupManager() Then I open python shell to test it: python manage.py shell from django.contrib.auth.models import Group t = Group.objects.all() Right after this command i'm getting error: File "<console>", line 1, in <module> File "/home/adrian/Dokumenty/Pycharm Projects/backend/venv/local/lib/python2.7/site-packages/django/db/models/manager.py", line 228, in all return self.get_queryset() File "/home/adrian/Dokumenty/Pycharm Projects/backend/registration/models.py", line 13, in get_queryset return super(DefaultGroupManager, self).get_queryset().exclude(id__in=tests_ids) File "/home/adrian/Dokumenty/Pycharm Projects/backend/venv/local/lib/python2.7/site-packages/django/db/models/query.py", line 686, in exclude return self._filter_or_exclude(True, *args, **kwargs) File "/home/adrian/Dokumenty/Pycharm Projects/backend/venv/local/lib/python2.7/site-packages/django/db/models/query.py", line 695, in _filter_or_exclude clone.query.add_q(~Q(*args, **kwargs)) File "/home/adrian/Dokumenty/Pycharm Projects/backend/venv/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1310, in add_q clause, require_inner = self._add_q(where_part, self.used_aliases) File "/home/adrian/Dokumenty/Pycharm Projects/backend/venv/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1338, in _add_q allow_joins=allow_joins, split_subq=split_subq, File "/home/adrian/Dokumenty/Pycharm Projects/backend/venv/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1150, in build_filter lookups, parts, reffed_expression = self.solve_lookup_type(arg) File "/home/adrian/Dokumenty/Pycharm Projects/backend/venv/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1036, in solve_lookup_type _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta()) File "/home/adrian/Dokumenty/Pycharm Projects/backend/venv/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 246, in get_meta return self.model._meta AttributeError: 'NoneType' object has no attribute '_meta' I have no idea whats wrong :( I will appreciate any help! -
How to call a function with context in django CB list view?
This is my view: class viewbloglistview(LoginRequiredMixin,ListView): model = Blog paginate_by = 6 def get_template_names(self): if True: return ['blog/view_blogs.html'] else: return ['blog/blog_list.html'] def get_queryset(self): return Blog.objects.all().order_by('-blog_views')[:20] def get_context_data(self, **kwargs): context = super(viewbloglistview, self).get_context_data(**kwargs) context['categories_list'] = categories.objects.all() return context This is my function: def categories_count(self): categories_count = categories.objects.annotate(blog_count=Count('blogs')).values_list('Title','blog_count') return categories_count I want call the function in my views with a context name to render the activity in my template.. Can anyone please help me out to solve this problem?? Thank you -
Django - How to make dynamic changes to template variables using Ajax
I have a remove_from_cart function which can successfully delete items. But the problem is that the item_list from a ListView won't be updated automatically after removing items unless I manually reload the page. How can I achieve this goal without reloading the page. Is possible to modify the value of variables in Django template by using Ajax? How can I assign updated_list from the function view to item_list? cart/cart_items.html: <script> $(document).ready(function () { $(".remove").click(function (event) { var book_id = $(this).parent().find('.idInput').val(); event.preventDefault(); $.ajax({ url: '{% url "cart:remove_from_cart" %}', type: "POST", dataType: 'json', data: { bookID: book_id, }, success: function (response_data) { $("#cartButton").text("Cart" + "(" + response_data.quantity + ")"); }, error: function (response_data) { alert('error occurred'); } }); }); }); </script> {% for book in item_list %} <div class="items"> <p id="title"> {{ book.book.title }}, quantity: {{ book.quantity }} </p> <form method="post"> {% csrf_token %} <input class="idInput" value="{{ book.id }}" hidden> <button class="remove" type="submit"> Remove</button> </form> </div> {% endfor %} cart/views.py: @csrf_exempt def remove_books(request): cart = Cart.objects.get(user=request.user) if request.method == 'POST': passed_id = request.POST['bookID'] secured_id = int(passed_id) book = BooksInCart.objects.get(id=secured_id) book.delete() response_data = { 'quantity': BooksInCart.objects.filter(cart=cart).aggregate(item_quantity=Sum('quantity'))['item_quantity'], 'updated_list': BooksInCart.objects.filter(cart=cart), } return JsonResponse(response_data) -
Understanding this django based geo query - F('friendly_rate') and km ? unorderable types: F() < int()
I am starting with geoDjango and I am following this tutorial which basically gives an insight on how we can filter out users within a specific distance of a Point type. A lot of the things is new to me but I am able to make sense of it. However the part at which a geo based query is made. Which is given below raises a few questions. This is the query candidates_inside_finder_radius_and_vice_versa = candidates.filter( last_location__distance_lte=( finder_location, D(km=min(finder.prefered_radius, F('friendly_rate')))) ).distance(finder_location).order_by('distance')[:limit] The following part from the above query is confusing me D(km=min(10, F('friendly_rate'))) 1-What is Km ? Will this search for finder.prefered_radius within km ? If so how do I convert it to miles ? 2-What is a friendly_rate ? Also when I run this query it gives me the following error stating D(km=min(10, F('friendly_rate')))) TypeError: unorderable types: F() < int() Any suggestions on how I can fix it ? -
is it possible to use class based view instead of function based view wagtail?
i'm still struggling to integrate django wagtail to an existing project. i'm only using wagtail for my blog page. and i want to create a form to create new post for my blog from my wagtail page. the way i create this is using an routablepage. here's some of my code i'm using this as my reference models.py class BlogIndex(RoutablePageMixin, Page): ... @route(r'^send-post/$', name='send_posts') def submit(self, request): from .views import submit_news return submit_news(request, self) ... class BlogPage(Page): ... forms.py class NewsPageForm(forms.ModelForm): ... views.py def submit_blog(request, blog_index): ... is it possible to change submit_blog function into create view ? because i've tried to make create view before and try something like this but it doesn't work because it will recursive to call the BlogPage Page in models.py models.py class BlogIndex(RoutablePageMixin, Page): ... @route(r'^send-post/$', BlogCreate.as_view(), name='send_posts') views.py class BlogCreate(CreateView): ... thank you very much -
where to store large data instead of cookies
I am developing an application(django 1.11.10) in which there is a module called RoleBasedAccessControl so i after user login i have soo much data(permission data in json format) from database(mysql) which defines different type of permission on different resource types. i searched on internet and got several option like "client side storage", "indexedDb" etc.. which can store large data to client side but i am not sure that i can access my permission data at server whenever required(as i can do with cookies using getCookies but cookies have limit of 4 kb) So my issue is where to manage that permission json data so both server and client can access to check whether following permission is valid or not if user trying to perform any action and this data can get bigger bigger is size as creating more resources by user. Other wise i need to hit db request from both client(via ajax) and server to check the particular permission before user can perform any action. Please suggest me a way to manage my permission json data where should store it. -
How can i make my serializer more dynamic
Here is my models.py from __future__ import unicode_literals from django.db import models class User(models.Model): name = models.CharField(max_length=200) company_name = models.ForeignKey('Company',on_delete=models.CASCADE,related_name='user') def __str__(self): return self.name class Company(models.Model): name = models.CharField(max_length=200) phone_number = models.IntegerField(null=True,blank=True) def __str__(self): return self.name class Catalog(models.Model): name = models.CharField(max_length=200) no_of_pcs = models.IntegerField(null=True,blank=True) per_piece_price = models.DecimalField(null=True,blank=True,max_digits=10,decimal_places=2) company_name = models.ForeignKey(Company,on_delete=models.CASCADE,related_name='catalog') def __str__(self): return self.name here is my serializers.py from rest_framework import serializers from .models import * from django.db.models import Sum,Count class CatalogSerializer(serializers.ModelSerializer): total_pieces = serializers.SerializerMethodField() total_price = serializers.SerializerMethodField() class Meta: model = Catalog fields = ('name','no_of_pcs','per_piece_price','company_name','total_pieces','total_price') def to_representation(self, instance): rep = super(CatalogSerializer, self).to_representation(instance) rep['company'] = { "company_name":instance.company_name.name, "phone_number":instance.company_name.phone_number, "company_id":instance.company_name.id } return rep def get_total_pieces(self, obj): totalpieces = Catalog.objects.aggregate(total_pieces=Count('no_of_pcs')) return totalpieces["total_pieces"] def get_total_price(self, obj): totalprice = Catalog.objects.aggregate(total_price=Sum('per_piece_price')) return totalprice["total_price"] here is my views.py from __future__ import unicode_literals from django.http import HttpResponse from .models import * import json from django.http import JsonResponse, HttpResponse from .serializers import * from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework import viewsets class CatalogView(viewsets.ModelViewSet): queryset = Catalog.objects.select_related('company_name') serializer_class = CatalogSerializer How can i make my serializers more dynamic instead of doing manually(rough way). is there any better way to do that?