Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django AWS RDS Postgres TTFB too slow
I have a Django app that uses two databases. One database is hosted on AWS, that I use to manage the users (users email and password). Then there is a second db that is using sqlite3 that is stored in the users laptop (local database). The app is ran locally (not hosted on a server). The only query that is done for the database hosted on AWS, is when the user logins. After that, all the queries are down on the local database. The local database has no relation to the database hosted on AWS. I don't know why but when I use the database hosted on AWS I get a high TTFB. Does anyone know how I can reduce this time? Oddly enough if I use a local data instead of the one running on AWS I get way faster TTFB. Thanks! -
Install Django Taggit Inside Another App?
I am using Django taggit. Initially, I created a tags app and customized taggit slightly. It's not a lot of code and doesn't warrant it's own app (in my opinion) so I want to move the tags code to another app (let's call it content). from content.utils import slugifier class Tag(TagBase): """This is a replacement class for the Taggit "Tag" class""" class Meta: verbose_name = _("tag") verbose_name_plural = _("tags") app_label = "tags" def slugify(self, tag, i=None): slug = slugifier(tag) if i is not None: slug += "-%d" % i return slug class TaggedItem(GenericTaggedItemBase, TaggedItemBase): # This tag field comes from TaggedItemBase - CustomTag overrides Tag tag = models.ForeignKey( Tag, on_delete=models.CASCADE, related_name="%(app_label)s_%(class)s_items", ) class Meta: verbose_name = _("tagged item") verbose_name_plural = _("tagged items") app_label = "tags" index_together = [["content_type", "object_id"]] unique_together = [["content_type", "object_id", "tag"]] class Content(PolymorphicModel): ... tags = TaggableManager(through=TaggedItem, blank=True) My Problem When I go to makemigrations, I get this error: (venv) C:\Users\Jarad\Documents\PyCharm\knowledgetack>python manage.py makemigrations SystemCheckError: System check identified some issues: ERRORS: content.Content.tags: (fields.E300) Field defines a relation with model 'Tag', which is either not installed, or is abstract. I think this error message is pretty clear and good. My app content has a model named Content which has … -
Django ORM Left Join onto same table
I have a custom permissions system in a django project that can link any user to any specific model instance to grant permission on that object. It is more complex than this, but boiled down: class Permission(models.Model): user = models.ForeignKey(User) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') I want to query for all permissions for any user, that are linked to the same content_object(s) that a particular user has been granted permission(s) on. Phrased differently, the user in question wants to see who else has permissions on any of the same objects that they do. In SQL, the following does the trick: SELECT perm1.* FROM app_permission perm1 LEFT JOIN app_permission perm2 ON perm2.user_id = 12345 AND perm1.content_type_id = perm2.content_type_id AND perm1.object_id = perm2.object_id WHERE perm2.id IS NOT NULL; Is it possible to achieve this in the django ORM? -
How can create/set a celery task to be executed in an unknown moment in the future?
I'm using celert tasks and python in my app. I want set or create a celery task to be excecuted in the future, but I don't know yet the exact moment, and I want to have the task id already. How can I do that? -
Django Formset `extra` field value take huge time to load the page
I have 320 form_cell-s in my webpage. Each form_cell is clickable and associated with a single Django formset. Each of the cells of the routine is acting as a form of the formset. So there are no add form button as you see. User can fill up any form_cell at any time and put necessary information. In views.py I declare the formset like below. ClassFormSet = modelformset_factory( Class, max_num=320, extra=320, can_delete=True ) My Class model has total 5 fields. And in my template I have to render all forms like this. <div hidden id="routineForm" > {{ formset.management_form }} {% for form in formset %} {{ form|crispy }} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endfor %} </div> Problem So, here what I understand is Django is rendering all of my 320 forms at a time and this is hugely slowing down loading my webpage. What steps should I take to save my webpage from loading for long time. -
Couldn't find reference 'path' in imported module
I have tried importing the files but I'm getting the same error,can someone help me out? It does allow to import path from urls. Django version: 3.2.8 Python version: 3.9.2 The ss is attached below. importerror. -
Do Arithmetic Operations in Django Model itself
I want to subtract two model fields in the model itself. Example : class Purchase(models.Model): name = models.CharField(max_length=80, unique=True) quantity = models.IntegerField(max_length=100, null=True) scheme = models.IntegerField(max_length=100, null=True) rate = models.IntegerField(max_length=100, null=True) discountPercent = models.IntegerField(max_length=100, null=True) discount = models.IntegerField(max_length=100, null=True) gst = models.IntegerField(max_length=100, null=True) value = models.IntegerField(max_length=100, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) product_image = models.ImageField(upload_to='product_image/', null=True, blank=True) FinalPrice = .....? class Meta: ordering = ('-date_created',) def __str__(self): return self.name Here I want to subtract field name "rate" and "discountPercent" and store its result in a new field named "FinalPrice". I tried to do it in views but I want to it in model itself. Please Guide me for this. -
DJango: I have an account in the database, but writes about its absence
Django error: django.contrib.auth.models.User.DoesNotExist: User matching query does not exist. Views: def create_child_comment(request): user_name = request.POST.get('author') current_id = request.POST.get('id') text = request.POST.get('text') user = User.objects.get(username=user_name) content_type = ContentType.objects.get(model='post') parent = Comment.objects.get(id=int(current_id)) Comment.object.create( user=user, text=text, content_type=content_type, object_id=1, parent=parent, ) return render(request, 'base.html') Models: class Comment(models.Model): user = models.ForeignKey(User, verbose_name='Author', on_delete=models.CASCADE) text = models.TextField(verbose_name='Text comment') parent = models.ForeignKey( 'self', verbose_name='Parent comment', blank=True, null=True, related_name='comment_children', on_delete=models.CASCADE, ) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() timestamp = models.DateTimeField(auto_now=True, verbose_name='Data create comment') html: data = { user: ' {{ request.author.username }}', parentId: parentId, text: text, id: id, csrfmiddlewaretoken: csrftoken, } $.ajax({ method: "POST", data: data, url: "{% url 'comment_child_create' %}", success: function (data) { window.location.replace('/post-comments') } }) I don't understand what is wrong, I created a parent comment - there are no problems with it, it takes the publisher's account from the database and everything is fine, but when I try to create a child comment, it swears that this account allegedly does not exist. But this is unreal.. -
Filtering by query params in many to many relationship using drf
I have two models: class Book(models.Model): id = models.CharField(verbose_name="unique id", primary_key=True, max_length=256) title = models.CharField(max_length=256) published_date = models.CharField(max_length=128, blank=True, null=True) average_rating = models.IntegerField(blank=True, null=True, default=None) ratings_count = models.IntegerField(blank=True, null=True, default=None) thumbnail = models.URLField(verbose_name="thumbnail url", null=True, blank=True, default=None) class Author(models.Model): name = models.CharField(null=True, blank=True, max_length=256) books = models.ManyToManyField(Book, related_name='authors') What i want to achieve is that i want to filter api queries by using query params like this: 127.0.0.1/books?author='something' So my param is something in that case. I want to filter by names of authors and check if there are books that have relationship with this authors. Also it is important that there could be more than just one param at the time like this: ?author='something1'&author='something2' I have no idea how to achieve this. I'm trying with default filtering using get_queryset function in generic classes of DRF, but have no idea still. -
Django Caching when using @login_required
I'm using the decorator @login_required to only show the pages when a user is authenticated. However, I noticed my DB (hosted on AWS) is a bit slow because of this request. Every time the user goes to a new page and the decorator @login_required is called, it makes a query to the DB. I would like to cache this, so that the it's not necessary to check all the time. How can I achieve this? Thank you! -
Pass Django Choices or Foreign Key data to Vue 3
I have the following code: from django_countries.fields import CountryField .... class Book(models.Model): country = CountryField() authors = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='instances') cover = models.CharField(choices=BOOK_COVER_CHOICES, max_length=64) .... The regular Django serializer would display the fields in the Django API as dropdowns. Is there a way to get that information straight from the same Django API view and use it in Vue 3? Or do I have to perform Vue->Django API request for each field to get the needed information? -
'NoneType' object is not iterable - pyModbusTCP.client
I am making a program in django python that reads tags from a plc by modbus, the program reads a table where the ip addresses and the addresses of registers are found, it makes a loop and in each turn it inserts an address of a new register. Everything works perfectly in the first round when reading the first record, but the problem occurs when it analyzes the second record in the table with the loop, it returns 'None', which I do not understand since those records have already been individually validated and if they have as such a value, even running the same code and reading an individual tag if it works, the error occurs when I want to read several tags at the same time from a table with a loop. I use read_holding_registers to read the records and I use the library: from pyModbusTCP.client import ModbusClient This is my code: while True: try: queryset_modbus = tagopc_link_device.objects.filter(tag_type='MODBUS').values_list('id', 'tag_name', 'tag_type', 'source_ip_address', 'source_ip_port', 'register_len', 'modbus_type', 'device_id', 'digitalinput_id') if queryset_modbus: utility.logInfo('modbus', 'Reading Tags from model - modbus', "INFO") try: for row in queryset_modbus: #Parameters ... tag = row[1] modbusAddress = int(tag) - 1 longitud = row[5] # Parameters Modbus ... modbus … -
Cannot access the foreignkey data in datatables
I have provided the javascript below. Please note the one with name "teacher". This teacher is basically a foriegn key. However when I try to console.log the row, it doesnt show me that particular array value as an object or the data returned as an object and instead it returns a string since it uses def __str__ on django models. Hence im not able to get the particular value, i.e teacher.first_name or in this case data.first_name P.S. Im using django-datatables-view for providing the ajax url. $(document).ready( function () { $('.table').DataTable({ "columnDefs": [ { name: 'date_created', orderable: true, searchable: true, targets: [0], }, { name: 'name', orderable: true, searchable: true, targets: [1], }, { name: 'email', orderable: true, searchable: true, targets: [2], }, { name: 'phone', orderable: true, searchable: true, targets: [3], }, { name: 'course', orderable: true, searchable: true, targets: [4], }, { name: 'remarks', orderable: true, searchable: true, targets: [5], }, { name: 'teacher', orderable: true, searchable: true, targets: [6], render: function(data, type, row){ return data.first_name + "<br>(" + data + ")" } }, { name: 'is_enrolled', orderable: true, searchable: true, targets: [7], render: function(data, type, row){ if (data === "True"){ return "<i class='fa fa-check text-success text'></i>" } else{ … -
JOIN ILLUMINATI SECRET SOCIETY +27710571905
JOIN ILLUMINATI SECRET SOCIETY +27710571905 in South Africa, Uganda, Zambia, Zimbabwe, UK, USA, Canada, Malawi,Botswana, Swaziland, South Sudan and in cities like Sasolburg,Limpopo,Witbank,Standarton,Secunda,Middelburg,Johannesburg,Vanderbijlpark,Secunda,Soweto Cape Town,Burgersfort, Polokwane,Thohoyandou, phalaborwa, mokopane, bochum, lebowakgomo, mankweng, Seshego, dendron, Giyani, Lephalale, musina,Alexandra Johannesburg,New york,Ohio,California,New mexico,London,Manchester,Liverpool,Kampala,Kigali,Lenasia, Midrand, Randburg, Roodepoort,Sandton, Alberton ,Germiston, Benoni, Boksburg ,Rakpan Daveyton, Duduza ,Edenvale, Impumelelo, Isando Katlehong, Kempton Park, KwaThema ,Nigel Reiger,Park Springs, Tembisa, Thokoza, Tsakane, Vosloorus ,Wattville ,Atteridgaeville,Centurion,Hammanskraal, Irene, Mamelodi ,Pretoria,Soshanguve,Boipatong, Bophelong,Evaton,Sebokeng, Sharpeville,Vereeniging, Meyerton,Heidelberg,Ratanda,Bronkhorstspruit,Ekangala,Kungwini,Bronberg,Cullinan,Refilwe,Zithobeni,Carltonville,Khutsong,Kagiso,Kromdraai,Krugersdorp,Magaliesburg, Muldersdrift, Mohlaken,Randfontein,Bekkersdal,testonaria,Kimberley,Upington,Kuruman,Sprinbok,Kathu Ritchie Pietermaritzburg,Bellville,Bloemfontein. If you're ready to join the great brotherhood of illuminati secret society kingdom today the door is open for new members. Headquarters at South Africa and USA kindly inbox the Great brotherhood illuminati Prof Bob. Email address now bobspells96@gmail.com Or contact him on whats-app mobile now +27710571905 for more information. https://illuminatiwithprofbob.blogspot.com/ A cash price reward of $100 million US dollars after your initiation. 2. A new sleek dream car will be given to you after you have received your benefit. 3. A dream House bought in the country of your own choice. 4. One Month holiday (fully paid) to your dream tourist destination. 5. One Year Golf Membership Package. 6. A V.I.P treatment in all Airports in the world. 7. A total lifestyle change. 8. … -
How to serve WASM files in Django
I compiled my C file to wasm using: emcc main.c -s USE_SDL=2 -O3 -s WASM=1 -o main.js I'm only using WASM to manipulate a canvas. There is no JS code other than the "glue" js code. I now have a directory (outside of Django, just somewhere in my Documents folder) with these files: - home.hml - main.c - main.js - main.wasm Which I can serve using whatever webserver eg python3 -m http.server 8000 --bind 127.0.0.1 And view the animation in the browser. And it works. No problems so far. I want to serve home.html from Django now. My URLs.py has: path('', views.home, name='home'), and views.py has: def home(request): context = {} return render(request, 'app/home.html', context) I have copied home.html to app/templates/app I then copied main.js to app/static/app Then I modified home.html to replace: <script src="main.js"></script> With <script src="{% static 'app/main.js' %}" type="text/javascript"></script> I don't know what to do with main.wasm. Should this also go into the static folder or into the project root? Do I need to add an explicit import somewhere for this? How can I get my home.html to behave the same as it was with a simplehttpserver, but when being served from Django? Please note that all … -
Why isn't my page redirecting after I submit the form or refresh the page in Django?
I am working on a Django application but I am not getting the desired results. The create_job page is not rendering after I submit the the form or refresh the entire page. This is the create_job_page view def create_job_page(request): current_customer = request.user.customer if not current_customer.stripe_payment_method_id: return redirect(reverse('customer:payment_method')) # return render(request, 'customer/create_job.html') # Filtering create_job = Job.objects.filter(customer=current_customer, status=Job.CREATING_STATUS).last() step1_form = forms.JobCreateStep1Form(instance=create_job) if request.method == 'POST': if request.POST.get('step') == '1': #If it's form one step1_form = forms.JobCreateStep1Form(request.POST, request.FILES) if step1_form.is_valid(): creating_job = step1_form.save(commit=False) # Adding current customer to the form creating_job.customer = current_customer creating_job.save() return redirect(reverse('customer:create_job')) return render(request, 'customer/create_job.html', { "step1_form": step1_form }) This is the HTML code <b>Create a Job</b> <div class="tab-content" id="pills-Content"> <div class="tab-pane fade" id="pills-info" role="tabpanel" aria-labelledby="pills-info-tab"> <h1>Item Info</h1> <form method="POST" enctype="multipart/form-data"> <b class="text-secondary">Item Information</b></br> <div class="card bg-white mt-2 mb-5"> <div class="card-body"> {% csrf_token %} {% bootstrap_form step1_form %} </div> </div> <input type="hidden" name="step" value="1"> <button class="btn btn-primary" type="submit">Save & Continue</button> </form> </div> -
Displaying LONGBLOB images in django template
I already inserted image as LONGBLOB datatype into the database and now trying to display the image by converting LONGBLOB to image in django template, How to do it? using MySQL Database views.py items=Products.objects.all() return render(request, 'display.html',{'itemLists':items}) display.html {% for item in itemLists %} <div class="box product-img"> <img src="data:image/jpg;charset=utf8;base64,{{item.image}}" alt="{{item.name}}"> <h3>{{item.name}}</h3> </div> {% endfor %} Got stucked in this code, How to do it? Any idea about How to decode the image in template itself ? -
NET::ERR_CERT_COMMON_NAME_INVALID error on GCP hosted Django site on email reset request using SendGrid. Namecheap domain
I've built a Django site which is hosted on GCP App Engine with SendGrid as email host. When resetting the password and clicking on the link in the following email, the subsequent error is thrown: Your connection is not private NET::ERR_CERT_COMMON_NAME_INVALID I've looked into several potential causes (linked at the end) but haven't been able to find a solution. password_reset_email.html (only displaying the reset_link block) {% block reset_link %} {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} {% endblock %} settings.py ALLOWED_HOSTS = ['*'] # Also tried with #ALLOWED_HOSTS = ['*', 'website.com', 'www.website.com'] # HTTPS settings SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_SSL_REDIRECT = True # HSTS settings SECURE_HSTS_SECONDS = 31536000 # 1 year SECURE_HSTS_PRELOAD = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True # Email backend settings (SendGrid) EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' DEFAULT_FROM_EMAIL = 'some@email.com' EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'apikey' EMAIL_HOST_PASSWORD = 'EMAIL_HOST_PASSWORD' EMAIL_PORT = 587 EMAIL_USE_TLS = True I have authenticated the domain and branded the link on SendGrid which have been verified over the DNS records on Namecheap. When I look at the certificate in the browser it still refers to *.sendgrid.net though. Perhaps this might be causing it? I thought authentication and link branding would solve that. I've … -
Django 3.2.7 - NoReverseMatch at /blog/ Reverse for ' latest_posts' not found. ' latest_posts' is not a valid view function or pattern name
While following a tutorial from "Coding For Everybody - Learn wagtail", i ran into a problem while messing with the Routable Pages video, which i copypasted the code found at his GitHub into my Blog and now the following error appears: Reverse for ' latest_posts' not found. ' latest_posts' is not a valid view function or pattern name. Request Method: GET Request URL: http://localhost:8000/blog/ Django Version: 3.2.7 Exception Type: NoReverseMatch Exception Value: Reverse for ' latest_posts' not found. ' latest_posts' is not a valid view function or pattern name. Exception Location: C:\Users\pedro.garcia\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix Python Executable: C:\Users\pedro.garcia\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.6 Python Path: ['C:\\Users\\pedro.garcia\\website\\mysite', 'C:\\Users\\pedro.garcia\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\pedro.garcia\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\pedro.garcia\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\pedro.garcia\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\pedro.garcia\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages'] Server time: Fri, 15 Oct 2021 13:28:15 +0000 My latest_posts.html: {% extends "base.html" %} {% load wagtailimages_tags %} {% block content %} <div class="container"> <h1>Latest Posts</h1> {% for post in posts %} <div class="row mt-5 mb-5"> <div class="col-sm-3"> {% image post.blog_image fill-250x250 as blog_img %} <a href="{{ post.url }}"> <img src="{{ blog_img.url }}" alt="{{ blog_img.alt }}"> </a> </div> <div class="col-sm-9"> <a href="{{ post.url }}"> <h2>{{ post.custom_title }}</h2> {# @todo add a summary field to BlogDetailPage; make it a RichTextField with only Bold and Italic enabled. #} <a href="{{ post.url }}" … -
Cache Django related field in running Python process
class Publisher(models.Model): name = models.CharField(max_length=200) class Book(models.Model): publisher = models.ForeignKey(Publisher, on_delete=models.PROTECT) name = models.CharField(max_length=255) There is a DRF serializer that returns the books and publisher associated with the book. There are thousands of books whereas only a hundred publishers. The data distribution is 1:1000 and hence it makes sense to store publisher objects in Python app cache after the first load till the next app restart. How can I cache the publisher using lru_cache in Python? Constraints and other info I'm already using Django cache with redis backend for other purposes and I don't think redis would give a significant boost(same network call + lookup). Adding custom manager to the Publisher model with get, filter, all doesn't help. all method gets called while related field lookup happens but there is no id in the instance to find the lookup. The object lookup happens in the related description get. Is there a way to change the behavior without writing custom Field? -
Is using django-rest-framwork secure? [closed]
I want to use django rest framework to build an API which allows a website I'm making to access a database. How do I make it so that only that website can access the api(or that I at least know who is accessing it). -
How to run custom function when object deleted in StackedInline?
I have 2 models: User and Photo, Photo is StackedInline into User in admin panel. I want to run my custom function when any photo of a user is deleted. I have overridden method save_model in admin.py. def save_model(self, request, obj, form, change): photoset = request.FILES.getlist('photo') if len(photoset) == 0: obj.save() else: obj.save() for file in photoset: user_image = UserImage(user=obj) user_image.photo.save(file.name, file) user_image.save() my_custom_function() I know that when I delete a photo I get into if block, but now if block works only when User doesn't upload any image when registring. I know about signals but I'm sure it's my case. Is it possible to achieve this result in save_model method? Thanks in advance! -
Add Product immediately in Order (shop without cart) [django]
I make a store, without a cart, that is, an order is immediately created and saved to the database as order, but it looks like a cart. My models: STATUSES = ( ('NEW', 'New'), ('PROGRESS', 'Progress'), ('DONE', 'Done), ) class Order(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) email = models.EmailField() phone = models.CharField(max_length=20) delivery_time = models.DateTimeField() address = models.CharField(max_length=200) comment = models.TextField() created_at = models.DateTimeField(auto_now_add=True) is_paid = models.BooleanField(default=False) user = models.ForeignKey(User, on_delete=models.CASCADE, null-True) status = models.CharFiels(max_lenght=20, choises=STATUS class Meta: ordering = ['-created_at'] def __str__(self): return f'Order: {self.id} on name {self.first_name} {self.last_name}' def get_total_cost(self): return sum(item.get_cost() for item in self.items.all()) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='order_items', on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) def __str__(self): return f'{self.id}' def get_cost(self): return self.product.price * self.quantity class Product(models.Model): title = models.CharField(max_length=100, db_index=True, unique=True) slug = models.SlugField(max_length=150, db_index=True) category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) photo = models.ImageField(upload_to='photos/', blank=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=7, decimal_places=2') in_stock = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['title', '-created_at'] index_together = (('id', 'slug'),) def __str__(self): return self.title def get_absolute_url(self): return reverse('shop:detail', args=[self.pk, self.slug]) I need a views, for add product in Order. Any help needed. Who could do that. Or who has seen something similar somewhere. … -
filter a select with the data of another select all in a modal
form class EserciziForm(forms.ModelForm): class Meta: model = models.DatiEsercizi exclude = ['gruppo_single'] class GruppiForm(forms.ModelForm): class Meta: model = models.DatiGruppi exclude = ['gruppi_scheda'] views def creazione(request, nome): scheda = get_object_or_404(Schede, nome_scheda = nome) eserciziFormSet = formset_factory(EserciziForm, extra = 0) if request.method == "POST": #gruppi gruppo_form = GruppiForm(request.POST, prefix = 'gruppo') if gruppo_form.is_valid(): gruppo = gruppo_form.save(commit = False) gruppo.gruppi_scheda = scheda gruppoName = gruppo_form.cleaned_data['dati_gruppo'] gruppo.save() #esercizi esercizi_formset = eserciziFormSet(request.POST, prefix='esercizi') for esercizi in esercizi_formset: esercizi_instance = esercizi.save(commit = False) esercizi_instance.gruppo_single = get_object_or_404(DatiGruppi, gruppi_scheda = scheda.id, dati_gruppo = gruppoName) esercizi_instance.save() return HttpResponseRedirect(request.path_info) else: #filtro esclusione gruppi già aggiunti gruppi_db = Gruppi.objects.all() group_to_add = Gruppi.objects.exclude(dati_gruppo__gruppi_scheda = scheda) GruppiForm.base_fields['dati_gruppo'] = forms.ModelChoiceField(queryset = group_to_add) gruppo_form = GruppiForm(prefix = 'gruppo') esercizi_formset = eserciziFormSet(prefix='esercizi') context = {'scheda' : scheda, 'gruppo_form' : gruppo_form, 'esercizi_formset': esercizi_formset, 'gruppi_db': gruppi_db} return render(request, 'crea/passo2.html', context) I have to filter the second select having using the first one. this code is inside a modal and the blue box (see photo) are form sets. how can i do to filter the data? From what I understand it is necessary to use AJAX I accept all the solutions but the answers without its use are more welcome as it is not very practical. -
is using multiples databases in django help performance?
Hi i have created a web app.inside my project have 3 more apps(Profile,Post,Comment) and for all of them i use one database in mysql.My question is:is using three databases(Profile_db,Post_db,Comment_db) will make some differences instead of using one database ?.I mean in the performance side.