Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Complex objects passed as args/kwargs between class based views in Django
I currently have a SessionWizardView from formtools package implemented. class DataframeFormView(SessionWizardView): def done(self,form_list): params={} for form in form_list: params.update(form.cleaned_data) return HttpResponseRedirect(reverse('download',kwargs={'params':params})) Everything is working fine in the forms view, and when the forms are successfully filled the above mentioned function runs, however I need to pass the params argument to another view: from django_downloadview import VirtualDownloadView, VirtualFile class DataframeDownloadView(VirtualDownloadView): def get_file(self): ### Access params dictionary here!!!! return VirtualFile(tfile.name, name=tfile.name) Thing I've tried: 1) override __init__ to add self.params = kwargs.pop('params') 2) create method to access to kwargs specific key params using return self.kwargs['params'] 3) Mixin solution (probably badly implemented but I thing there are constraints in these two CBVs) Ultimately, suing method 1 and 2, I manage to access merely to a string representation of the params dictionary through reversing to download/url/. I need a more programatically solution to obtain the original dict object. TLDR: How can I pass complex objects between views. Best regards, -
Django Dynamic formset inline form jQuery selector error
I'm using https://github.com/elo80ka/django-dynamic-formset/blob/master/src/jquery.formset.js With the following defaults: <script src="{% static 'flights/jquery.formset.js' %}"></script> <script type="text/javascript"> $(function() { $('#approach_form table tr').formset({ prefix: 'approach_set', formCssClass: 'approach-formset' }); }) </script> Form html: <div class="form-group"> <div class="input-group-sm"> <label class="text-muted">Approaches</label> <div class="form-control pl-4 pt-2"> {% for formset in inlines %} {% for form in formset %} {{ form.id }} <div id="approach_form" class="row"> {{ form.errors }} <table> <tr> <td>{{ form.approach_type }}</td> <td>{{ form.number }}</td> <td>{% if form.instance.pk %}{{ form.DELETE }}{% endif %}</td> </tr> </table> </div> {% endfor %} {{ formset.management_form }} {% endfor %} </div> </div> </div> The create view renders properly but my update view does this: Rendered HTML: <div id="approach_form" class="row"> <table> <tbody><tr class="approach-formset"> <td><select name="approach_set-0-approach_type" id="id_approach_set-0-approach_type"> <option value="">---------</option> <option value="ILS">ILS</option> <option value="CATII">CAT II</option> <option value="CATIII">CAT III</option> </select></td> <td><input type="number" name="approach_set-0-number" value="2" min="0" id="id_approach_set-0-number"></td> <td><input type="hidden" name="approach_set-0-DELETE" id="id_approach_set-0-DELETE"><a class="delete-row" href="javascript:void(0)">Remove</a></td> </tr> <tr class="approach-formset-add"><td colspan="3"><a class="add-row" href="javascript:void(0)">Add</a></td></tr></tbody></table> </div> Like I said, the CreateView renders properly, without the 2 extra 'Add' rows, but this UpdateView adds the extra 2 'Add' links. Thanks in advance for taking the time to look at this. -
Django: split form in pages using formtools and save to data base
I've a form that has 3 sections: 1) tamanios (sizes), 2) cantidades (quantities), 3) archivos subids (Upload Image). I need to separate 1 & 2 in one page, and 3 in a different page, and save form data to data base. As far as I've investigated this is possible using formtools. But using formtools I've had to split my model into 2 models: a) TamaniosCantidades, b) ArchivosSubidos, so they can be rendered in different "steps". Nevertheless, I'd prefer to have only 1 model. But it's ok if the solution contains some ForeingKey to connect both splitted models. What I need to do in order to save the form as a model object in data base? I can think of on how to write the 'done' method in my Wizard Class. Original model: class TamaniosCantidades(models.Model): TAMANIOS = (('2x2', '2" x 2"',), ('3x3', '3" x 3"',), ('4x4', '4" x 4"',), ('5x5', '5" x 5"',)) CANTIDADES = (('50', '50',), ('100', '100',), ('150', '150',)) tamanios = models.CharField(max_length=10, choices=TAMANIOS) cantidades = models.CharField(max_length=10, choices=CANTIDADES) imagenes = models.FileField(upload_to='imagenes/') uploaded_at = models.DateTimeField(auto_now_add=True) Modified models (splited result): class TamaniosCantidades(models.Model): TAMANIOS = (('2x2', '2" x 2"',), ('3x3', '3" x 3"',), ('4x4', '4" x 4"',), ('5x5', '5" x 5"',)) CANTIDADES = … -
Associating ImageField url with another object in django
I have two models, class Core: def logo_path(instance, filename): pattern = re.compile(r'\s+') filename = re.sub(pattern, '', filename) return 'images/core/logos/core_{0}/{1}'.format(instance.pk, filename) name = models.CharField(db_index=True, max_length=255) logo = models.ImageField(upload_to=logo_path, blank=True, null=True) and class CoreRoom(Room): core = models.ForeignKey(Core, on_delete=models.CASCADE, null=True logo_url = models.CharField(max_length=1024, null=True) I want to populate the logo_url in the CoreRoom object with the path to the logo in the Core object. How do I do this? -
ExpressionWrapper inside Annotate is not working in django
When i run this it gives me an error "TypeError: 'F' object is not iterable" Resources is the model i have which has a field title and similar is a function to check the ratio of similarity between 2 strings -
Accessing Cleaned Data of one form inside a second form
So I have two forms, Sale and SaleItems SaleForm = SaleForm(request.POST or None, auto_id=False, prefix = 'SaleForm') SaleItemsForm = modelformset_factory( Sale, form = SaleItemsForm, formset = ItemsFormSet, extra=1, can_delete=True ) once they're both given POST data and valid, they're in the usual statement: if SaleForm.is_valid() and SaleItemsForm.is_valid(): pass When it comes time to do validation I've superseded the basemodelformset and want to write my own custom clean method for the modelformset. I want to use cleaned data from SaleForm inside the clean method for the ItemsFormSet: from django import forms class ItemsFormSet(forms.models.BaseModelFormSet): def __init__(self, *args, **kwargs): super(ItemsFormSet, self).__init__(*args, **kwargs) def clean(self): super().clean() print(TheSaleForm.cleaned_data['Value']) This doesn't work, and I've tried a few dumb things: try to make SaleForm a global and access it between the views.py and forms.py modules. That was a bad idea and now I understand more about the module scope try to import the actual object, again not smart I'm assuming there has to be a way to do this without saving the cleaned data off somewhere to the database and retrieving it again in the clean method of the formset. I'm not sure if overwriting ItemsFormSet.is_valid() and trying to allow a kwarg dictionary item to be passed … -
django. how can i do some math in model
i'm trying to migrate from php to django, for my study project. User can create 3 variables such as minimal value, maximal value and step for this value. from it i 'm generate list, and then i'm trying to do some math and results render as table, but can't understend how to do it right. This is my scary prototype code on python: import numpy as np mcharge = np.arange(0.01, 0.38, 0.01) charge = np.arange(20, 57, 1) mdiscount = np.arange(0.001, 0.013, 0.001) discount = np.arange(5, 23, 1.5) clist = charge.tolist() mlist = mcharge.tolist() mdlist = mdiscount.tolist() dlist = discount.tolist() result_sum_n_m_n = [(x + y) / 100 for x,y in zip(charge, margin)] result_sum_s_m_s = [(x + y) / 100 for x,y in zip(mdiscount, discount)] result_sum_a = [ '%.4f' % elem for elem in result_sum_n_m_n ] result_sum_b = [ '%.4f' % elem for elem in result_sum_s_m_s ] n_m_n = result_sum_a * 12 n_m_n.sort() s_m_s = result_sum_b * 37 n_m = [float(i) for i in n_m_n] s_m = [float(i) for i in s_m_s] multiply = [(x * y) for x,y in zip(n_m, s_m)] minus = [(x- y) for x, y in zip(n_m, s_m)] last_minus = [(x - y) for x, y in zip(minus, … -
How can I pass Python list to Javascript in HTML level
I'm trying to pass Python list to use it as Javascript array in HTML file, but when I check the passed Python list in Javascript level, the console log says it's string. I'm trying to do that in Django environment. Django views.py def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['names'] = list( Store.objects.values_list('businessName', flat=True)) return context index.html <span data-names="{{ names }}">...</span> <script> console.log(type($('span').attr('data-names'))); </script> The console says it's string type. Did I miss any middle step there? -
SQL formatting/escaping injection with raw(...)
I am using a query in django. While I normally do this directly in the sql connector, sometimes I use the raw(...) method, for example as follows: items_from_master = list(ItemMaster.objects.raw( """SELECT * FROM main_itemmaster WHERE (content_type_id != 'TV Season') AND (MATCH(name) against('%s')) LIMIT 20 UNION SELECT * FROM main_itemmaster WHERE name='%s' ORDER BY imdb_votes DESC LIMIT 30""" % (q,q))) Is there a way to escape the string here? For example, something like cursor.execute(sql, params)? -
How to change django manage.py default shell
I've just installed Anaconda and what's annoying that after executing: python manage.py shell The IPython shell is used. I'd like to change it back to default Python distribution. I'm using Visual Studio Code and already changed it interpreter to default python 3.6. Moreover the python command runs normal python distribution, and the problem exists both in Visual Studio and normal cmd terminal. -
Django API beyond simple data handling
I have a django application that deploys the model logic and data handling through the administration. I also have in the same project a python file (scriptcl.py) that makes use of the model data to perform heavy calculations that take some time, per example 5 secs, to be processed. I have migrated the project to the cloud and now I need an API to call this file (scriptcl.py) passing parameters, process the computation accordingly to the parameters and data of the DB (maintained in the admin) and then respond back. All examples of the django DRF that I've seen so far only contain authentication and data handling (Create, Read, Update, Delete). Could anyone suggest an idea to approach this? -
What types of validations are automatically handled by Django Rest Framework?
Lets say I have a model defined as follows: from django.core.validators import MinValueValidator, MaxValueValidator, RegexValidator alphanumeric_validator = RegexValidator(r'^[a-zA-Z0-9]*$', 'Only alphanumeric characters are allowed.') class Person(model.Model): name = models.CharField(max_length=60, validators=[alphanumeric_validator]) number = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(100)]) email = models.EmailField() Now, lets say I am serializing and creating MyModel objects using Django Rest Framework. It looks like like this: from rest_framework import serializers from .models import Person from rest_framework.response import Response class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person fields = ('name', 'number', 'email') class PostPerson(APIView): def post(self, request, format=None): serializer = PersonSerializer(data=request.data) if serializer.is_valid(): serializer.save()= return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Now, my question is this: when I am validating the serializer using is_valid(), does DRF handle the validators=[alphanumeric_validator], and validators=[MinValueValidator(0), MaxValueValidator(100)]? Also, I am sure DRF automatically handles the max_length property, but does it also check if the email is an actual email address using the proper regex? I am generally just confused about clean, full_clean, and all the methods that are called during form validations and serializer validations, so would like to get some solid explanations. Thanks in advance. -
How to update from within a model method
I have the following method I am trying to write: class MTurk(models.Model): ... def parse(self, url): res = requests.get(url) node = html.fromstring(res.content) data = MTurk()._parse_page(node) self.update(**data) However, when I try and do self.update(**data) it tells me: AttributeError: 'MTurk' object has no attribute 'update' Normally I would do MTurk.objects.filter(pk=self.pk).update(**data), but is there a way to do this from within the model method itself without having to re-call everything? -
How to access a Django method from Angular 7
Im pretty new to full stack development so this might actually be an easy question: I want to be able to access a simple method in the models.py file of my Django backend: def testMethodFromModelPY(request, path=''): data = {'returnedData': 'whatever'} return data I add the path to the method in urls.py: from django.urls import path from DjangoBackEnd import models urlpatterns = [ # some other paths here that frontend is able to access # path(r'api/v1/', models.testMethodFromModelPY, name='testMethodFromModelPY'), ] Now, within Angular frontend I create a component called config in the app folder and add to config.service.ts export interface Test { returnedData: string; } @Injectable() export class ConfigService { constructor(private http: HttpClient) { } testMethodInConfigServiceTS() { return this.http.get('/api/v1/testMethodFromModelPY/'); } } I include this Service in app.module.ts and call the testMethodInConfigServiceTS function in config.component.ts: testMethodInConfigComponentTS() { this.configService.testMethodInConfigServiceTS() .subscribe( (data: Test) => this.test = { ...data }, // success path error => this.error = error // error path ); } Within config.component.html I try to access this method with: <button (click)="testMethodInConfigComponentTS()">teststuffhere</button> But when I clic a button I get the errormessage: GET http://127.0.0.1:8000/api/v1/testMethodFromModelPY/ 404 (Not Found) thanks a lot! -
Retrieving pk from filtered Django QuerySet
I have a Sample model that is searched via a web interface and a QuerySet of criteria-matching Sample objects are returned as expected. model class Sample(models.Model): sample_name = models.CharField('Sample', max_length=16) html form <form name="sample_search_form" method="GET" action="{% url 'search' %}"> <input id="sample_search_box" type="text" name="sample_search_box" placeholder="Search samples..." > <button id="sample_search_submit" type="submit" >Submit</button> </form> views def search(request): if request.GET: search_term = request.GET['sample_search_box'] results = Sample.objects.filter(sample_name__icontains=search_term) return render_to_response('samples/sample_search_list.html', {'results': results}) return render_to_response('samples/sample_search_list.html', {'results': results, 'search': results}) I would also like to return the models' primary key for additional purposes. I tried variations on below. results = Sample.objects.filter(sample_name__icontains=search_term).get(sample_name_id=pk) But I get an error similar to: name 'pk' is not defined How can I guard the filtration method as written AND also get the primary key value? Thanks in advance. -
Django serializing all objects in JSONB
I am trying to serialize a model for displaying on an existing front end interface. The model is setup as such: class Timevalue(models.Model): time = models.FloatField(blank=True, null=True) values = JSONField(blank=True, null=True) The nature of the values is that it has no defined keys, therefore it is using JSON rather than a structured schema. As an end result, I need to RestAPI to output a list of timevalue objects that is flattened so that each element contains the time key as well as all the keys for the values. So far I have written the following serializer that can return the data in the format of [{'time': 0.01, 'values': {'value1': 1, 'value2': 2, 'value3': 3}}] class TimevalueSerializer(serializers.Serializer): time = serializers.FloatField() values = serializers.JSONField() However I cannot achieve getting the output in the necessary format: [{'time': 0.01, 'value1': 1, 'value2': 2, 'value3': 3}]. I have tried the following serializer setup: class TimevaluechildSerializer(serializers.Serializer): fields = '*' class TimevalueSerializer(serializers.Serializer): time = serializers.FloatField() values = TimevaluechildSerializer('*') but I cannot work out what to pass to the child serializer in order for it to return all of the key-value pairs. As this model is used for other views, I prefer to use a Serializer rather than … -
Understanding Django managers
I have the following model in one of my django app (cards) : # cards/models.py from django.db import models from django.conf import settings class CardManager(models.Manager): def insert_base_owned_cards(user): cards = Card.objects.filter(isBaseCard=True) for card in cards: OwnedCard(card=card, user=user).save() class Card(models.Model): name = models.CharField(max_length=30) img = models.CharField(max_length=100) text = models.CharField(max_length=250) cardSet = models.CharField(max_length=30) rarity = models.CharField(max_length=30, default='Common') attack = models.IntegerField() health = models.IntegerField() cost = models.IntegerField() isBaseCard = models.BooleanField(default=False) def __str__(self): return self.name class OwnedCard(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) card = models.ForeignKey(Card, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): return self.card.name And I call like it in the users app model : # users/models.py from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from cards.models import CardManager class CustomUser(AbstractUser): # add additional fields in here credit = models.IntegerField(default=200) def __str__(self): return self.username @receiver(post_save, sender=CustomUser) def insertBaseCards(sender, instance, created, **kwargs): if created: CardManager.insert_base_owned_cards(instance) The code as is works, but I am pretty sure that I am not following the standards. From what I saw, I shouldn't call CardManager.insert_base_owned_cards(arg) but either Card.objects.insert_base_owned_cards(arg) or OwnedCard.objects.insert_base_owned_cards(arg) however since the method in the manager use both Card and OwnedCard, I am unsure as to how to do it. … -
Understanding django channels - QueryAuthMiddleware
How to write custom authentication of user in chat over ws:// protocol? The user on the other side of Django app is the mobile user, connecting websocket via ws:// . In Django channels docs it says: If you have a custom authentication scheme, you can write a custom middleware to parse the details and put a user object (or whatever other object you need) into your scope.Middleware is written as a callable that takes an ASGI application and wraps it to return another ASGI application. Most authentication can just be done on the scope, so all you need to do is override the initial constructor that takes a scope, rather than the event-running coroutine. Here’s a simple example of a middleware that just takes a user ID out of the query string and uses that: The same principles can be applied to authenticate over non-HTTP protocols; for example, you might want to use someone’s chat username from a chat protocol to turn it into a user. from django.db import close_old_connections class QueryAuthMiddleware: def init(self, inner): # Store the ASGI application we were passed self.inner = inner def __call__(self, scope): # Look up user from query string (you should also do … -
Order the objects in the field ManyToMany
gt.tests - ManyToMany field with model Test. I need to sort the tests by this strange algorithm, but the question is different. After all the operations, I get a sorted list of tests and add them to the ManyToMany field. But when I take the value tests from this field, they are displayed in order from the smallest id test to the largest. How do I add tests to this field in my order? tests = Test.objects.all() gt = GroupTest.objects.create(title=name, user=user) #code import random tests_array = [] tests_go = [] for reading in ReadingForTest.objects.all(): if tests.filter(reading=reading).count() != 0: tests_array.append(tests.filter(reading=reading)) tests_list = tests.filter(reading__isnull=True) while len(tests_list) > 0: number = random.randint(0, 5) tests_array.append(tests_list[:number]) tests_list = tests_list[number:] seq = [x for x in range(len(tests_array))] random.shuffle(seq) for i in seq: tests_go.extend(tests_array[i]) tests_go = tests_go[:number_of_questions] print_arr = [] for test in tests_go: print_arr.append(test.id) gt.tests.add(test) print(print_arr) print([x.id for x in gt.tests.all()]) Screenshot output here -
Change a boolean value after a click on a button in Django
I need some help regarding button clicks and boolean value changes. My model: class Topic(models.Model): subject = models.CharField(max_length=255) category = models.CharField(max_length=255) last_updated = models.DateTimeField(auto_now_add=True) starter = models.ForeignKey(User, on_delete=models.CASCADE, related_name='topics') slug = models.SlugField(unique=True) isReported = models.BooleanField(default=False) startPrice = models.IntegerField(validators=[RegexValidator(r'^\d{1,10}$')]) I want to change the state of the field "isReported" from the default value "False" to "True" after a click on a button: <button type="submit" class="btn btn-primary btn-block">Report</button> I already googled and found something like this on SO (How do I change a value in django on button click in HTML?) but I am lacking knowledge of the concept presented in this thread. Unfortunately this was the only helpful information I could find. How can I change the boolean value in my database after a single button click? It is not neccessary to change the value back on this button. -
Referring from the "many" field to the "one" in Django
A noob question. I have followed the official Django tutorial and I have the following: class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text I have tried replacing the Choice.str() code as follows: def __str__(self): return 'Choice for Q: {}'.format(Question.objects.get(pk=self.question_id_id).__str__()) The code works and when viewing the "Choices" in the "admin" section the related question is shown. Is doing it this way OK or could this cause an error in certain situations? Is there a better way of doing this? Many thanks. -
Django rest_auth - how to add custom password validation rules
Can someone explain how to alter the default password validation rules for Django's rest_auth library? I imagine this can be done by copying the existing serializers and adding custom validation there. (Link to rest_auth serializer documentation) I could dive into this myself, but I think this will cost me a lot of time, and it would be nice if someone can give me at least an explanation on a beginner level. Some people may think that I am lazy to even ask such a question, but please let's leave personal opinions out of this. I am quite a beginner programmer, diving into a lot of different technologies. A bit of help here and there can safe quite some time. Besides that I am quite sure there will be others who will be looking for this information. On my (React) frontend I am using the following validation rules, and I would like the backend to have the same: Password must contain at least: - one uppercase letter (A-Z) - one lowercase letter (a-z) - one of the following characters: !@#$&* - one number (0-9) Password must be at least 10 characters long Password can not contain other characters than the ones … -
Django Admin - How to convert delete action dropdown in a single button
I would like to 'transform' the action dropdown, that have the default delete option, in a single button, but keeping the rule of delete all the row that are checked. -
Is it possible to auto generate categories in Django ecommerce?
I wanted to generate categories in a Django e-commerce app. But I thought may be there is a library/module that can auto generate categories of itens for sale in ecommerce. -
How transfer search results to the next page using the django-filters ? Django
I'm trying to pass search results from one page to another using django-filters. How can I do this? What documentation describes it? My views.py def my_views(request): search_users = SearchWoman(request.GET, queryset=Woman.objects.all()) return render(request, 'index.html', { 'filter': search_users }) Filters.py class SearchCompany(django_filters.FilterSet): class Meta: model = Company fields = ['name_basic', 'trade', 'province'] Templates.html <form method="get"> {{ filter.form.as_p }} <button type="submit">Search</button> </form> {% for profile in filter.qs %} <li>{{ profile.name }} </li> {% endfor %} </ul> Any help will be appreciated.