Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Displaying the django updateview in a grid
I have created a small Django app where I have the following Model: class CourseBatch(models.Model): start_date = models.DateTimeField(null = True, blank = True) end_date = models.DateTimeField(null = True, blank = True) batch_name = models.CharField(max_length=50, default="Enter Batch Name") course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name="batches") trainer = models.ForeignKey(Trainer, on_delete=models.CASCADE, related_name="trainer") college = models.ForeignKey(College, on_delete=models.CASCADE, related_name="college") additional_notes = models.TextField(max_length=500, default="No_Points",blank=True) user = models.ForeignKey(User, verbose_name='user', on_delete=models.CASCADE, default=1) objects = models.Manager() class ChkListForBatch(models.Model): batch = models.ForeignKey(CourseBatch, on_delete=models.CASCADE, related_name="checklistitems") chkpoint = models.ForeignKey(CheckPoint, on_delete=models.CASCADE, related_name="chkpoint") chkpoint_done = models.BooleanField(default=False) updated_on = models.DateTimeField(null = True, blank = True) objects = models.Manager() def __str__(self): return self.chkpoint.description View class CheckListForBatch(LoginRequiredMixin, generic.UpdateView): model = ChkListForBatch form_class = ChkListForBatchForm template_name = 'checklistforbatch.html' def get_queryset(self): batch_id = self.kwargs.get('pk') print(self.kwargs.get('pk')) selected_batch = CourseBatch.objects.filter(id=batch_id) chkListItems = ChkListForBatch.objects.filter(batch=selected_batch[0]) return chkListItems #batch[0].checklistitems.all() Template {% extends 'base.html' %} {% block title %}My Batches{% endblock %} {% block content %} <h1>Batches</h1> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Sign up</button> </form> {% endblock %} This works fine and displays the form with combo boxes as shown in the image below The user will navigate to this screen from the batch list view by clicking on one of the batches. But, what I want is to display a grid or … -
I'm getting a TypeError while doing a clean function with super() [duplicate]
This question already has an answer here: TypeError: super() takes at least 1 argument (0 given) error is specific to any python version? 3 answers I'm trying to do a clean function to verify an email and used this code: from django import forms from django.core import validators class FormName(forms.Form): Name = forms.CharField() Email = forms.EmailField() VerifyEmail = forms.EmailField(label = 'Enter your email again') Text = forms.CharField(widget = forms.Textarea) def clean(self): all_clean_data = super().clean() email = all_clean_data['Email'] vemail = all_clean_data['VerifyEmail'] if email != vemail: raise forms.ValidationError("Make sure email matches!") when I try it out it I get a TypeError saying: super() takes at least 1 argument (0 given) ??? -
Django CreateView redirect to UpdateView if already have an object created
I have tried how to check(using get() function) inside CreateView. so when we try to access CreateView URL, this view will check is there an object has been created. if yes, it will redirect to that object UpdateView URL. but the problem is I don't know how to reverse it. 'urls.py app_name = 'product' urlpatterns = [ url(r'^$', pglist, name='list'), url(r'^create/$', pcreate, name='create'), url(r'^(?P<slug>[\w-]+)/$', pdetail, name='detail'), url(r'^(?P<slug>[\w-]+)/update/$', pupdate, name='update'), url(r'^redire/$', ered, name='redire'), ' 'views.py CreateView class def get(self, *args, **kwargs): if self.model.objects.get(user=self.request.user): return redirect("product:update", kwargs={'slug': ??? I HAVE NO IDEA HOW TO DOING THIS PART ???slug}) else: return redirect("product:create") ' if I change the line into ==> return redirect("pages:update"), CreateView URL show ' NoReverseMatch at /create/ Reverse for 'update' with no arguments not found. 1 pattern(s) tried: ['(?P<slug>[\\w-]+)/update/$'] ' so, what it should be? enter code here ' return redirect("product:update", kwargs={'slug': ??? I HAVE NO IDEA HOW TO DOING THIS PART ???slug}) ' -
How to send notification to a user using django?
I am creating a taxi-service project using Django with two users (driver/rider) and I would like to know how can I send a notification to a driver when the rider make a pickup request by entering his destination place I tried to learn about websockets and django channels but I don't know how to apply that in my project This is my Rider modal form and I want to send the notification (destination and number of places) to the driver when the rider clicks on ''Send NOW'' button <div class="text-center"> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="@mdo">Search for near Taxis </button> </div> <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header" style="background-color: #4abf3d;"> <h5 class="modal-title text-center font-weight-bold" id="exampleModalLabel">Saisir les coordonnées du voyage</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form> <div class="form-group"> <label for="destination" class="col-form-label">Destination:</label> <input type="text" class="form-control" id="destination"> </div> <div class="form-group"> <label for="nombreDePlaces" class="col-form-label">Number of places:</label> <input type="text" class="form-control" id="nombreDePlaces"> </div> </form> <div id="ajax-errors" class="alert alert-danger" role="alert" style="display: none;"> <strong>Whoops!</strong><br> <span>Something went wrong :/</span> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary btn-lg" id="demande_button"><span id="Commander_button">Send NOW</span><i id="Commander_icon" class="fas fa-taxi"></i></button> </div> </div> </div> </div> -
Can Django create automatic other objects if a new objects is created?
Based on that question: How to Create new object automatically after creating other object in django? I need a model that create automatic new objects while a new object is created. So I tried this class Book(models.Model): author = models.CharField(max_length=30) title = models.CharField(max_length=30) foo = models.IntegerField(default=0) def save(self, *args, **kwargs): is_new = True if not self.id else False super(Book, self).save(*args, **kwargs) if is_new: part_2 = Book.objects.create(author_id = self.author.id, title = self.title, foo = self.title + 1,) So my idea was that if I create a new Book instance it automatically creates a Book instance with the same data except foo, which should be raised. While trying to save a new entry I get a Recursion Error maximum recursion depth exceeded while calling a Python object Request Method: POST Request URL: http://localhost:8000/admin/bookcreator/book/add/ Django Version: 2.2 Exception Type: RecursionError Exception Value: maximum recursion depth exceeded while calling a Python object /Django/bookcreator/models.py in save title = self.title, foo = self.foo + 1,) -
Can we use same database for php and django?
Scenario There is an Android app running with php as backend and a webapp running with django. Both apps are designed to be used with same database. Can this approach create any issues ? -
Django GenericViewSet: Can't create custom routes
I'm struggling to understand how class-based generic views work in Django. The documentation doesn't cover generic views in detail. I've created a custom @list_route but there seems to be no way of calling it. Here's the code: view: class AnalyticsViewSet(viewsets.GenericViewSet): queryset = models.BookingAnalytics.objects.exclude(status=booking_constants.BookingState.deleted) permission_classes = [DRYPermissions, ] filter_backends = [DjangoFilterBackend, ] filter_class = filters.AnalyticsFilter serializer_class = serializers.AnalyticsDetailSerializer serializer_classes = {} def list(self, request, *args, **kwargs): if not request.user.is_role_admin: raise exc.PermissionDenied() queryset = self.get_queryset() filtered_queryset = self.filter_queryset(queryset) data = { 'stats': { .... } } return response.Ok(data) @list_route(methods=['POST'], url_path='export') def export(self, request, *args, **kwargs): queryset = self.get_queryset() filtered_queryset = self.filter_queryset(queryset) recipients = [] if 'recipients' in request.data: recipients = request.data['recipients'] .... return response.NoContent() model: class BookingAnalytics(UUIDModel, TimeStampedModel): ... class Meta: verbose_name = _('booking analytic') verbose_name_plural = _('booking analytics') ordering = ('-booking_date', '-created',) def __str__(self): return self.uuid @staticmethod @authenticated_users def has_read_permission(request) -> bool: return request.user.is_role_admin or request.user.is_role_client @staticmethod @authenticated_users def has_write_permission(request) -> bool: return request.user.is_role_admin or request.user.is_role_client @staticmethod @authenticated_users def has_object_list_permission(request) -> bool: return request.user.is_role_admin @authenticated_users def has_object_export_permission(self, request) -> bool: return request.user.is_role_admin Here, the default list route works just fine. However, the export route isn't called at all. What is it that I'm missing? -
How do I not have a long list of html in the url when implementing a navigation bar?
I have designed a navigation bar using a base.html, styles.css, and main.js. I have used in it about.html and contact.html through {%block content%} ... {%endblock%} But when I click on the navigation bar that links me to About, for example, it would go to whichever page I am on (ex. contact page i.e. http://127.0.0.1:8000/contact/) and then add the html (http://127.0.0.1:8000/contact/about.html) That leads to a lot of urls I have to add to urls.py (ex. contact/about.html and about/about.html for just getting to the about page) Is there any way to simplify this? This is my urls.py: from django.contrib import admin from django.urls import path from home.views import about, contact urlpatterns = [ path('admin/', admin.site.urls), path('about/', about), path('contact/',contact), ] this is my base.html: <!DOCTYPE html> <html lang="en"> <head> {% load static %} <link rel="stylesheet" href="{% static 'home/styles.css' %}"> <link href="https://fonts.googleapis.com/css?family=Poppins&display=swap" rel="stylesheet"> <meta charset="UTF-8"> <title>{%block name%}{% endblock %}</title> </head> <body> <header> <nav> <div class="logo"> <h4>Jinyang Zhang</h4> </div> <ul class="nav-links"> <li><a href="about.html">About</a></li> <li><a href="#">My Work</a></li> <li><a href="contact.html">Contact</a></li> </ul> <div class="burger"> <div class="line1"></div> <div class="line2"></div> <div class="line3"></div> </div> </nav> {%block content%} {%endblock%} </header> <script src="{% static 'home/main.js' %}"></script> </body> </html> I would like it to be, for example, when I click on the navigation "About" … -
Django-table2 and Django-filter is not filtering
I'm doing exactly like the documentation, but when I type a value in the "name" field and click on Filter, the page refreshes but nothing is filtered. Follow my code. filter.py class ClientFilter(django_filters.FilterSet): class Meta: model = Client fields = ['name'] views.py class RelatorioClientsView(FilterView, ExportMixin, CustomListView): template_name = 'relatorios/clients/geral.html' model = Client table_class = ClientTable context_object_name = 'all_clients' permission_codename = 'view_clients' filterset_class = ClientFilter def get_context_data(self, **kwargs): context = super(RelatorioClientsView, self).get_context_data(**kwargs) table = ClientTable(Client.objects.all()) table.paginate(page=self.request.GET.get('page', 1), per_page=15) context['table'] = table RequestConfig(self.request).configure(table) #ordena return context tables.py class ClientTable(ColumnShiftTable): class Meta: model = Client sequence = ('id', 'name') template_name = 'django_tables2/bootstrap.html' template.html {% load render_table from django_tables2 %} {% load bootstrap3 %} {% if filter %} <form action="" method="get" class="form form-inline"> {% bootstrap_form filter.form layout='inline' %} {% bootstrap_button 'filter' %} </form> {% endif %} {% render_table table' %} Here is the documentation part link for filter -
How to create a copy of a database per each new user signup
I have a 'master' database created with postgres, using django and react for everything else, it's got about 1000 different objects in it. When a new user signs up to my website, I want to give them a copy of the master database, in which they could crud all they want but not affect the master. If they are not logged in, then they can see the master, if they are logged in than they see their personal copy. This question is more around the theory and best practices. Storage size, speed, UI considered.. Does anyone have tips on how i should go about this? My first thought is to create a parent object in the database, one object for the master, and one object each new user's database copy. But the database could grow huge really fast. This is my first time experimenting with this so any details you want to shed would be extremely helpful. current structure all_items = { { "item": name, "detail: ['one', 'two', 'three'] }, { "item": second name, "detail: ['four', 'five', 'six'] } } Possible structure database={ {master : all_items = { { "item": name, "detail: ['one', 'two', 'three'] }, { "item": second name, … -
Javascript is not executing before form submit
I currently have a form, with two buttons, "add" and "submit". Using javascript, I'm adding more rows to the form whenever "add" is clicked. However it does not update the form until I click "submit". How do I get it to add the rows without hitting the "submit" button? <form method="post" id="formset"> <table> {% csrf_token %} {{ formset.management_form }} {{ formset }} <div id="empty_form"> <tr> {% for field in formset.empty_form.visible_fields %} <td>{{ field }}</td> {% endfor %} </tr> </div> </table> <button id="add_more" type="button">Add</button> <button type="submit" id="submit">Submit</button> </form> Javascript: $('#add_more').click(function() { var form_idx = $('#id_form-TOTAL_FORMS').val(); $('#formset').append($('#empty_form').html().replace(/__prefix__/g, form_idx)); $('#id_form-TOTAL_FORMS').val(parseInt(form_idx) + 1); }); -
Logical OR on F-expressions in Django ORM
I have a query like User.objects.annotate( x=Value(False, output_field=BooleanField()), y=Value(True, output_field=BooleanField()) ).annotate( z=F('x').bitor(F('y')) # HOW TO DO THIS? ).values('z') which works with SQLite but not with PostgreSQL. The error is LINE 1: SELECT (false | true) AS "z" FROM "auth_user" LIMIT 21 ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. How should I implement the logical OR on annotated fields that works consistently? Thank you. -
constantly getting "GET" on terminal
I'm not sure what's causing it, the front end(javascript) or the back end(python, django) On my terminal it constantly prints "GET" such as this [06/Jun/2019 00:49:13] "GET /inbox/notifications/api/unread_list/?max=5 HTTP/1.1" 200 38 [06/Jun/2019 00:49:29] "GET /inbox/notifications/api/unread_list/?max=5 HTTP/1.1" 200 38 [06/Jun/2019 00:49:45] "GET /inbox/notifications/api/unread_list/?max=5 HTTP/1.1" 200 38 [06/Jun/2019 00:50:01] "GET /inbox/notifications/api/unread_list/?max=5 HTTP/1.1" 200 38 [06/Jun/2019 00:50:17] "GET /inbox/notifications/api/unread_list/?max=5 HTTP/1.1" 200 38 [06/Jun/2019 00:50:33] "GET /inbox/notifications/api/unread_list/?max=5 HTTP/1.1" 200 38 [06/Jun/2019 00:50:49] "GET /inbox/notifications/api/unread_list/?max=5 HTTP/1.1" 200 38 -
Django filter drop down based on another drop down
All I'm trying to do filter the Sub-program dropdown based on which program is pressed. Currently, I'm using one to many relationships to save many subprograms under the program node. I thought this would handle things but it's simply returning all the subprograms regardless of which program is selected. views.py class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = fields = ['asset_name', 'road_name', 'suburb', 'lifecycle', 'program', 'subprogram', 'internal_budget', 'external_budget', 'budget_year', 'finance_description', 'project_description', 'reference_description', 'attachment'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) models.py class Program (models.Model): program_name = models.CharField(max_length=50, unique=True) def __str__(self): return self.program_name def get_absolute_url(self): return reverse('program-create') class SubProgram (models.Model): # program = models.OneToOneField(Program, on_delete=models.CASCADE, primary_key=True) program = models.ForeignKey(Program, on_delete=models.CASCADE) subprogram_name = models.CharField(max_length=50, unique=True) def __str__(self): return self.subprogram_name def get_absolute_url(self): return reverse('subprogram-create') class Post (models.Model): asset_name = models.CharField(max_length=150) road_name = models.CharField(max_length=150) suburb = models.CharField(max_length=150) lifecycle = models.CharField(max_length=20, choices=CYCLE_CHOICES) program = models.ForeignKey(Program, on_delete=models.CASCADE) subprogram = models.CharField(max_length=20, choices=SUBPROGRAM_CHOICES) internal_budget = models.IntegerField(blank=True) external_budget = models.IntegerField(blank=True) budget_year = models.CharField(max_length=20, choices=BUDGET_YEAR_CHOICES) budget = models.IntegerField(blank=True) finance_description = models.TextField() project_description = models.TextField() reference_description = models.CharField(max_length=150) attachment = models.FileField(blank=True) date_posted = models.DateTimeField(default=timezone.now()) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.asset_name def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) def save(self, *args, **kwargs): if not self.budget: self.budget = self.internal_budget + self.external_budget … -
Why doesn't Django Channels provide a SyncHttpConsumer?
They provide a Sync and Async version of all consumers, except http. They just provide an AsyncHttpConsumer. I would like this because I would like to use a SyncHttpConsumer to wrap a Django view. This would allow me to have one path (graphql/) handled by a django view for http requests, and a special websocket consumer for websocket requests. -
Values_list with flat=true still showing <QuerySet [..]>
I'm trying to print some query with values_list but for some reason it is still printing and I need to be gone and only have the list inside the square brackets... def resum(request): usuari=Usuari.objects.order_by('usuari_id').values_list('usuari_id', flat=True) print(usuari) and what i get printed is: <QuerySet [1, 2, 3, 4, 5, 6, 50, 51]> [06/Jun/2019 01:21:04] "GET /resum/ HTTP/1.1" 200 2102 Any idea?? Thanks! -
"Unable to log in with provided credentials" on HEROKU but not LOCALHOST
I have been working on a Django app on localhost and got the site where I was ready to push to Heroku. While running the site on localhost, I am able to successfully get an Auth Token from my internal API, and log the user in successfully. The moment I try to do this same action on the Heroku site, I get the error "Unable to log in with provided credentials." I am not sure why this is happening, maybe there is something specific to Heroku? INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'widget_tweaks', 'django_filters', 'rest_framework', 'rest_framework.authtoken', 'admin_settings', 'customer_settings', 'user', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ) } AUTH_USER_MODEL = 'admin_settings.User' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'app.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] -
How to pre-fill a Django model
Like : class Article (models.Model): user= models.ForeinkeyField('User', related_name="articles") def __init___(self): self.user = 'Friendy' -
Why multilanguages does not work on Ubuntu server?
Why does the local site work with i18n and I have links like a site.com/en type, and on the Ubuntu server the site.com link doesn’t work and the translation does not work? The set_language function also does not work. urls.py urlpatterns = [ path('admin/', admin.site.urls), url(r'^i18n/', include('django.conf.urls.i18n')), ]\ + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) \ + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += i18n_patterns( url(r'^$', views.index, name='index'), ) forms.py <form class="lang-form" action="{% url 'set_language' %}" method="post"> {% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}" /> <select name="language" onChange="this.form.submit();"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% for lang in LANGUAGES %} <option class="decorated" value="{{ lang.0 }}" {% if lang.0 == LANGUAGE_CODE %} selected="selected"{% endif %}> {% if lang.0 == 'uk' %} ua {% else %} {{ lang.0 }} {% endif %} </option> {% endfor %} </select> </form> settings.py ... LANGUAGES = ( ('uk', _('Ukrainian')), ('ru', _('Russian')), ) LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) TIME_ZONE = 'Europe/Kiev' USE_I18N = True USE_L10N = True USE_TZ = True -
Filtering Django superclass QuerySets based on the subclass having a specific field or not
In a simplified example, I have several models, one that I don't own because it's form a CMS package, called Page, and quite a few that I do own, with simplified code: class MyPage(Page): pass class MyBlogPage(Page): tags = models.WhateverField(default=something, etc) class NewsPage(Page): tags = models.WhateverField(default=something, etc) class DocumentationPage(Page): pass This duplicated code is, unfortunately, not a choice: it's there because of legacy code that's incredibly hard to extricate and refactor, and so this is what it is. I'd now like to find all related pages when I'm on either a blog or news page, so I figured I'd do that: related_pages = Page.objects.filter(tags__isnull=False).filter(tags__in=self.tags).exclude(pk=self.pk) And that crashes Django because not all instances of Page have a database column called tags, and isnull only works because it assumes the column exists, only testing whether the value for that field in the record is null or not. I can't for the life of me find any documentation that lets me test for the existence of a column first, before then chaining further filters that rely on it, so: is there a way to filter for objects that even have a specific column (in this case, tags) first, so that subsequent operations can … -
using models.manager to count the number of votes
I'm using models.manager to count the number of votes but I don't understand why the number of vote isn't showing off. the voting system works(checked with admin) but the manager isn't working. models.py class PostVoteCountManager(models.Manager): def get_query_set(self): return super(PostVoteCountManager, self).get_query_set.annotate( votes=Count('vote')).order_by("-votes") class Post(models.Model): rank_score = models.FloatField(default=0.0) with_votes = PostVoteCountManager() class Vote(models.Model): voter = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) def __str__(self): return "%s voted %s" %(self.voter.username, self.post.title) my views.py class PostListView(ListView): model = Post template_name = 'community/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' #ordering = ['-date_posted'] queryset = Post.with_votes.all() def get_context_data(self, **kwargs): context = super(PostListView, self).get_context_data(**kwargs) if self.request.user.is_authenticated: voted = Vote.objects.filter(voter=self.request.user) posts_in_page = [post.id for post in context["object_list"]] voted = voted.filter(post_id__in=posts_in_page) voted = voted.values_list('post_id', flat=True) context["voted"] = voted return context In html I do {% for post in posts %} <form method="post" action="{% url 'vote' %}" class="vote_form"> <li> [{{ post.votes }}] {{post}} {% csrf_token %} <input type="hidden" id="id_post" name="post" class="hidden_id" value="{{ post.pk }}" /> <input type="hidden" id="id_voter" name="voter" class="hidden_id" value="{{ user.pk }}" /> {% if not user.is_authenticated %} <button disabled title="Please login to vote">+</button> {% elif post.pk not in voted %} <button>+</button> {% else %} <button>-</button> {% endif %} </form> {% endform%} -
How to Save or Update values of a list in my model correctly?
I have the following models: class Tarifa_Sem (models.Model): limit_inferior_isr = models.DecimalField (max_digits = 10, decimal_places = 2) limit_superior = models.DecimalField (max_digits = 10, decimal_places = 2) cuota_fija_t = models.DecimalField (max_digits = 10, decimal_places = 2, blank = True) percentage_over_excess = models.DecimalField (max_digits = 10, decimal_places = 2) class Calculator_isr (models.Model): rate = models.ForeignKey (Rate_Sem, on_delete = models.CASCADE, null = True, blank = True, related_name = 'calculators') base_gravada = models.DecimalField (max_digits = 10, decimal_places = 2, null = True, blank = True) limite_inf_calculo = models.DecimalField (max_digits = 10, decimal_places = 2, null = True, blank = True) percentage_excent_li = models.DecimalField (max_digits = 10, decimal_places = 2, null = True, blank = True) fixed_ quota = models.DecimalField (max_digits = 10, decimal_places = 2, null = True, blank = True) I make a query by iterating my values of the base_gravada field. results = [ Tarifa_Sem.objects.filter (limite_superior__gte = obj.base_gravada) .values_list ('limite_inferior_isr', 'cuota_fija_t', 'percentage_sobre_excedente') . First () for obj in Calculadora_isr.objects.all () ] This query returns this list: [(Decimal ('133.22'), Decimal ('2.59'), Decimal ('6.40')), (Decimal ('8790.96'), Decimal ('1649.34'), Decimal ('30 .00 ')), (Decimal ( '2765.43'), Decimal ('292.88'), Decimal ('21 .36 ')), (Decimal (' 8790.96 '), Decimal (' 1649.34 '), Decimal ('30 .00'))] To save … -
Replacing django decorator commit_manually with non_atomic_requests
I have a Django view which imports an Excel file, and if exceptions occur I would like to catch them and report them all, and roll back any saves. I'm getting a TransactionManagementError even though I have used the non_atomic_requests decorator. As I'm also using the login_required decorator I thought they might be interfering with each other. First I reversed the order then I removed the login required. No change. I've tried disabling automatic transactions globally. Maybe I didn't do it right but it's not the solution I want anyway. I removed the offending line of code (see below) but the same error occurred when I tried to rollback It is running on Python 3.7.3 with the latest Django and using SQLlite. I'm running it as a unit test right now, although perhaps I'm abusing the term. Suffice to say it's running as a Django TestCase. @transaction.non_atomic_requests @login_required(login_url='/accounts/login/?next=/finance/gl_upload/') def gl_upload(request): transaction.set_autocommit(False) if upriv(request.user, ['admin', 'finance']) == 'admin': if request.method == 'POST': ... file processing here ... except Exception as e: errs.append(format('Exception "{1}" at row {0}\n'.format(p['rownum'], e))) if errs: transaction.rollback() rows_deleted = 0 rows_inserted = 0 print(''.join('Error: {0}\n'.format(e) for e in errs)) else: transaction.commit() rows_deleted = Gldata.objects.filter(item='Actual', period_gte=older, period_lte=newest).delete() rows_inserted = … -
Pass variable to href template in Django 2
I have below function in my views.py Django 2 project and I am trying to pass the variable "stylefolder" from views.py to my base.html template in order to dynamically get the correct href in my link tag. Below is my current code: def home(request): products = Product.objects.order_by('-votes_total') paginator = Paginator(products, 10) page = request.GET.get('page') paged_listings = paginator.get_page(page) context = { 'products':paged_listings, 'stylefolder': 'cryptoblog/style.css' } return render(request,'home1.html', context) In the base.html file, I have below code. href="{% static '{{ stylefolder }}' %}"> The problem is that when I look into the view:Source section of the page, I get as a result: <link rel="stylesheet" type="text/css" href="/static/%7B%7B%20stylefolder%20%7D%7D"> instead of below desired result: <link rel="stylesheet" type="text/css" href="/static/cryptoblog/style.css"> What should I change to get "/static/cryptoblog/style.css" in the href tag? -
What causes DRF Viewsets to perform inefficient SQL queries?
Background: In switching away from function based DRF endpoints to class-based views / viewsets I am finding that class-based views perform slightly better without nested relations and much worse with nested relations. Pseudocode Model Context: Creator: ForeignKey.Shipments[] Unit: ForeignKey.Shipments[] Shipment: ForeignKey.Addresses[] ForeignKey.Creator ForeignKey.Unit Address: Street City State Noteworthy Serializer Context: Unit: Meta: Depth = 1 Creator: Meta: Depth = Infinite When comparing Viewsets of the above structure to the equivalent @apiview, I'm finding: /addresses performs slightly better on SQL querycount (0.9x), with 1.1x CPU overhead (expected) /creators performs slightly worse on SQL querycount (1.1x), with 3.9x CPU overhead (expected) /creators/1 with a Read-Only Viewset performs slightly better on SQL querycount (0.9x), with 3.4x CPU overhead (unexpected) /creators/1 with a Writeable Viewset performs significantly worse on SQL querycount (3.3x), with significant 5.9x CPU overhead (unexpected) /units/1 with a Writeable Viewset performs profoundly worse on SQL querycount (4.4x), with a massive 7.9x CPU overhead (VERY unexpected) Both forms of viewsets do not benefit from / disregard prefetch_related usage from get_queryset entirely (VERY unexpected) Breakdown of retrieve against @apiview: (240 queries including 235 similar and 120 duplicates) Breakdown of retrieve against viewsets.ReadOnlyModelViewSet: (208 queries including 200 similar and 78 duplicates ) Breakdown of …