Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django PostgreSQL Partitioning reference error
We have two models. I'm implementing partitioning on the PaymentModel. It gives an error when I want to add to the BuyerModel table linked to this table; insert or update on table "betik_app_payment_buyermodel" violates foreign key constraint "betik_app_payment_bu_payment_id_d7022880_fk_betik_app" DETAIL: Key (payment_id)=(2) is not present in table "betik_app_payment_paymentmodel". models.py @architect.install('partition', type='range', subtype='date', constraint='month', column='dt') class PaymentModel(models.Model): class Meta: app_label = 'betik_app_payment' indexes = [ models.Index(fields=['user_email']) ] payment_status = models.PositiveIntegerField(default=1) price = MoneyField(max_digits=20, decimal_places=2) dt = models.DateTimeField() user_email = models.EmailField(null=True, blank=True) token = models.CharField(max_length=255, null=True, blank=True) class BuyerModel(models.Model): class Meta: app_label = 'betik_app_payment' indexes = [ models.Index(fields=['name', 'surname']) ] payment = models.OneToOneField(to='betik_app_payment.PaymentModel', on_delete=models.CASCADE,related_name='buyer') name = models.CharField(max_length=100) surname = models.CharField(max_length=100) email = models.EmailField(null=True, blank=True) ip = models.GenericIPAddressField(null=True, blank=True) main.py from datetime import datetime from djmoney.money import Money buyer_name="Name" buyer_surname="Surname" buyer_email="developer@betik.com.tr" buyer_ip="10.0.0.1" price= Money("100.00","TRY") payment_instance = PaymentModel.objects.create( price=price, dt=datetime.now(), user_email=buyer_email ) # raise error at here buyer_instance = BuyerModel.objects.create( payment=payment_instance, name=buyer_name, surname=buyer_surname, email=buyer_email, ip=buyer_ip ) using library: money partition I'm looking at the tables in the database with the pgadmin tool and the partition has been applied successfully. data added in both tables. But BuyerModel table is empty PaymentModel table has two triggers. These triggers are created automatically by the architect library. Maybe there … -
How to allow only custom urls in Django rest api?
I'm trying to create a simple api to learn how Django works. I'm using rest_framework. First, I have created a model: class User(models.Model): username = models.CharField(max_length=20, primary_key=True) password = models.CharField(max_length=50) token = models.UUIDField(default=uuid.uuid4, editable=False) creation_dt = models.DateTimeField(auto_now_add=True) Then I have created a serializer: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'password', 'token', 'creation_dt') read_only_fields = ('creation_dt', 'token',) And then, in api.py, this code: class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() permission_classes = [permissions.AllowAny] serializer_class = UserSerializer http_method_names = ['get', 'post'] @action(methods=['POST'], detail=False, permission_classes=[permissions.AllowAny], url_path='get_all_users') def get_all_users(self, request, pk=None): ... return Response(UserSerializer(self.queryset[:user_number], As you can see, I added a custom url_path "get_all_users". So, everything works until here. My problem is that I can still access "/users/", "/users/user_name", POST users etc, the normal CRUD app. The question is, how can I allow only the url I have especifially created and block all the rest created automatically? Thanks. -
django_filters - Filters are not responsive (function based view)
Trying to implement a filter django_filters to an existing function based view. The filter is rendering as it should, but nothing is happening. There is a few question on the topic, so I am going to answer some potential questions: I used $ pip install django-filter I installed in my virtual environment Filter.py is installed in the same app as the views Something to mention in my filters.py, import django_filters is underlined in red ("Import "django_filters" could not be resolved"). I cant find why, but this could be a strong contender in the root cause of the problem. Settings file INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "crispy_forms", 'main.apps.MainConfig', 'django_filters', models class Catalogue(models.Model): product = models.ManyToManyField('Product', blank=True) product_title = models.TextField('Product Title', blank=True) class Meta: db_table='Catalogue' def __str__(self): return str(self.product_title) filters import django_filters from .models import * class CatalogueFilter(django_filters.FilterSet): class Meta: model = Catalogue fields = ['product_title'] views from .filters import CatalogueFilter def show_venue(request, venue_id): if request.method == "POST" and 'btnreview_form' in request.POST: form = CatalogueReviewForm(request.POST) if form.is_valid(): data = form.save(commit=False) data.product_id = venue_id # links to product ID in Catalogue Model and return product name data.venue_id = request.POST.get('venue_id') # prints venue ID in form data.user_id = request.user.id data.save() … -
Django Migrations: How to mark a migration as a parent of other apps migrations?
I'm trying to create a new Django application whose migrations depends on other apps migrations. I want migrations on the other apps to have a dependency on migrations on the new application, even when the new application doesn't reference at all the models at the other apps. For example, let's say I have application A (an existing app) and application B (my new application): A has a migration called A.0001, and B has a migration called B.0001 which depends on A.0001. I now make a change at A.MyModel, so I need to run python manage.py makemigrations to generate a new migration A.0002. What I want is A.0002 to automatically depend on B.0001. How can I specify this dependency on new migrations in A without having to do it by hand each time I modify a model in A? I tried to add empty modifications of models in A at the migration B.0001, but I haven't got it to work and it looks very hacky to me. -
How to handle Invalid base64-encoded string error with fernet decrypt?
class MyModel(models.Model): value = models.CharField(max_length=255) I am trying to encrypt this field in the db. def encrypt_value(val): key = settings.ENCRYPT_KEY.encode() f = Fernet(key) return f.encrypt(val.encode()) MyModel.objects.create(value=encrypt_value(val)) # saves into the db like this `\x674141414141426a72584c714e355574383343337937636a41666e4d714f357034535464394e5f6b395461524975692d7346696f586b34586d78694a5a485f314c6e696854776e6d7548645a5451765f7a66324139446a334c724c7475694b424b524753454b4c4b5f34705a50535246784a56416b70383d` decypt value model = MyModel.objects.get(id=1) value = decrypt_value(model.val) def decrypt_value(val): key = settings.ENCRYPT_KEY.encode() f = Fernet(key) return f.decrypt(val).decode() But with decrypt getting InvalidToken: error -
How to fix UNIQUE constraint failed: users_profile.user_id?
How to fix UNIQUE constraint failed: users_profile.user_id? already have a created profile views.py class EditProfile(CreateView): model = Profile context_object_name = 'profile' template_name = 'users/profile_edit.html' fields = ['avatar', 'name', 'description'] success_url = reverse_lazy('users:profile') def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) urls.py path('<slug:slug>/edit/', EditProfile.as_view(), name='profile_edit'), models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(upload_to='users/avatars/%Y/%m/%d/', blank=True) name = models.CharField(max_length=20, blank=True) description = models.CharField(max_length=250, blank=True) slug = models.SlugField(max_length=50, blank=True) def __str__(self): return f"{self.user}" def save(self, *args, **kwargs): self.slug = slugify(self.user) super(Profile, self).save(*args, **kwargs) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver def save_profile(sender, instance, **kwargs): instance.profile.save() -
Not able to find template in Django Framework
As part of a project, I'm developing a social networking website. When I try to load a webpage, a django.template.exceptions error message appears. TemplateDoesNotExist. I have examined every setting, installed application, and template directory item in relation to their position. Everything was running smoothly without any issues up until yesterday. When I began working today, I started running across this issue. The location in the errors is exactly right, thus I don't understand how it can't locate the template. Additionally, I have four templates, of which two (the recently built ones) are experiencing this issue while the other two load without any issues.[Images of Error I am facing right now](enter image description here) I am trying to display a HTML file and expecting to come over on my browser. -
Compare vlaue in django template
I want to compare a value in Templete if it is same insert data in database and if not leave it empty. {% if {{DB_product_query.exec_summary}} == 'True' %} <div class="form-group row"> <label class="col-sm-2 col-form-label">Executive summary</label> <div class="col-md-10 col-sm-10 col-xs-12"> {{ form.executive_summary }} </div> </div> {% endif %} Error::: Could not parse the remainder: '{{DB_product_query.exec_summary}}' from {{DB_product_query.exec_summary}}' already checked DB_product_query.exec_summary return True -
Django View Test With PUT Method
I am testing my Django App and I have used APIView to have all HTTP requests go to one endpoint. I have managed to test the GET and POST but testing the PUT I am getting {"detail":"Unsupported media type \\"application/octet-stream\\" in request."} when I print response.content with AssertionError: 415!=200. Below is my code; def test_view_province_exists(self): user = User.objects.create_superuser(firstname='John', lastname='Doez', email='johndoez@mail.com', role='System Admin', access_url='chikoloadmin.kodkon.com', password='Passwordz123') self.client.login(email='johndoez@mail.com', password='Passwordz123') prov = Province.objects.create(province='Southern', created_by=user) response = self.client.put(self.province_url, data={'province': 'Southern Province', 'public_key': prov.public_key}) print(response.content) self.assertEqual(response.status_code, 200) self.assertContains(response, 'Province Updated.') -
Font-face imported font not loading on webpage (django)
I've got a django web app running and am trying to upload a custom font. I'm using @font-face in the style sheet to grab the font files and then am using inline styling in the html template to apply the font (for some reason using body{} in the style sheet doesn't apply styles to the entire page). @font-face code in style sheet: @font-face { font-family: 'D3 Digitalism'; src: local('D3 Digitalism') url('static/chatswap/font/d3-digitalism-font/D3Digitalism.woff2') format('woff2'), local('D3 Digitalism'), url('static/chatswap/font/d3-digitalism-font/D3Digitalism.woff') format('woff'), local('D3 Digitalism'), url('static/chatswap/font/d3-digitalism-font/D3Digitalism.eot'), local('D3 Digitalism'), url('static/chatswap/font/d3-digitalism-font/D3Digitalism.ttf') format('truetype'); font-weight: normal; font-style: normal; font-display: swap; } index.html template: <body style="background-color: rgb(20,20,20); font-family: D3 Digitalism"> I've tried changing the name of the font in the CSS file to something without a number or space character in the name, did not help. -
How to efficiently display objects related to specific foreign key?
I have separate models for authors and theses and the author model has a foreign key to the thesis model. My question is how can I efficiently display the authors for each thesis? This is my models.py for the author and thesis class thesisDB(Model): thesis_id = models.AutoField(primary_key=True, blank=True, null=False) title = models.CharField(max_length=200, blank=True, null=True, unique=True) adviser = models.CharField(max_length=200, blank=True, null=True) published_date = models.DateField(blank=True, null=True) class Authors(Model): thesis = models.ForeignKey(thesisDB, on_delete=models.CASCADE,) first_name = models.CharField(max_length=200, blank=True, null=True) last_name = models.CharField(max_length=200, blank=True, null=True) middle_initial = models.CharField(max_length=2, blank=True, null=True, validators=[initial_validator]) I am currently doing this method where I loop through all the authors and match their foreign key id to the thesis id in thesisdb model so I can display the right authors for each thesis. {% for post in thesis_details %} <p class="m-0"><i class="bi bi-person pe-1"></i>Authors: {% for author in authors %} {% if author.thesis.thesis_id == post.thesis_id %} <span class="me-1">{{author.first_name}} {{author.middle_initial}} {{author.last_name}}</span> {% endif %} {% endfor %} </p> {% endfor %} But this doesn't seem efficient. Is there a better way of doing it? -
Django, nginx StreamingHttpResponse Giving 502 Time Out
I am not able to figure it out why server is crashing below is the code class Echo: def write(self, value): return value @api_view(['GET']) @permission_classes([AllowAny, ]) def export_report(request): import csv from django.db import connection cursor = connection.cursor() try: cursor.execute('select query here') except Exception: cursor.close() raise echo_buffer = Echo() def cursor_generator(cursor, selected_fields, echo_buffer, arraysize=30): 'An iterator that uses fetchmany to keep memory usage down' writer = csv.writer(echo_buffer) header = True while True: if header: header = False yield writer.writerow(['first_nama', 'last_name']) results = cursor.fetchmany(arraysize) if not results: cursor.close() break for result in results: yield writer.writerow(result) response_list = [] response = StreamingHttpResponse(cursor_generator(cursor, selected_fields, echo_buffer), content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="report.csv"' return response -
Django admin show user who uploaded document
Can anyone please send me in the right direction? I have a django project without frontend so to speak. At the moment all I need is admin page. My users are able to upload documents, but there is no way for me to show for users who uploaded any given document. I managed to get a dropdown menu where user can choose who uploaded it. But that is not the goal. I want to achieve "uploaded by xxx" where "xxx" is the active (logged in) user. I fail to find correct keywords for google search and such. Can anyone drop a link to some tutorial/documentation? I have added this line to my "document" model. uploaded_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) After I add "uploaded_by" to fieldsets in admin.py I get a dropdown menu where I can choose form all users. -
In Dajngo, Class based views does not render HTML in template-Is context missing?
``I started to work with class based views, but the codes that I've written initially does not render in the template when I use class based views. The data that is in main_c.main_categories.url, main_c.name (see template) simply does not show up when I use class based views. When I change back to function based views and refresh the page, the HTML code in the template shows up without any problems. Could someone explain what causes this error? I've read something about context not been found by the template but I don't really understand what it means and how context resolves the issue. Thanks in advance!` views.py class MainCategoryDeleteView(DeleteView): model = MainCategory success_url = reverse_lazy("main_category") template_name = 'admin_dashboard/categories/maincategory_confirm_delete.html' class MainCategoryUpdateView(UpdateView): model = MainCategory fields = '__all__' success_url = reverse_lazy("main_category") template_name = 'admin_dashboard/categories/main_category_edit.html' class MainCategoryCreateView(CreateView): model = MainCategory fields = '__all__' success_url = reverse_lazy("main_category") template_name = 'admin_dashboard/categories/main_category.html' def get_context_data(self, **kwargs): context = super(MainCategoryCreateView, self).get_context_data(**kwargs) context['main_categories'] = MainCategory.objects.all() print(MainCategory.objects.all()) return context urls.py path('BaitSouq/MainCategory/', views.MainCategoryCreateView.as_view(), name="main_category"), path('BaitSouq/MainCategory/<int:pk>/Delete/', views.MainCategoryDeleteView.as_view(), name="main_category_delete"), path('BaitSouq/MainCategory/<int:pk>/Change/', views.MainCategoryUpdateView.as_view(), name="main_category_update"), templates <div class="col-lg-2 d-none d-lg-flex"> <div class="categories-dropdown-wrap style-2 mt-30"> <div class="d-flex categori-dropdown-inner" style="font-size: x-small"> <ul> {% for main_c in main_categories %} <li> <a href="#"> <img src="{{ main_c.main_categories.url }}" alt=""/>{{ main_c.name }}</a> </li> … -
How to show history of orders for user Django
I will pin some screenshots of my template and admin panel I have history of orders in admin panel but when im trying to show it in user profile in my template that`s not working and i got queryset Im sorry for russian words in my site, i can rescreen my screenshots if you need that models.py class Order(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT, related_name='orders', verbose_name='Заказы', default=1) username = models.CharField(max_length=50, verbose_name='Имя пользователя') email = models.EmailField() vk_or_telegram = models.CharField(max_length=255, verbose_name='Ссылка для связи', default='vk.com') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False, verbose_name='Оплачено') class Meta: ordering = ['-created',] verbose_name = 'Заказ' verbose_name_plural = 'Заказы' def __str__(self): return 'Заказ {}'.format(self.id) def get_cost(self): return sum(item.get_cost() for item in self.items.all()) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='order', on_delete=models.CASCADE) product = models.ForeignKey(Posts, related_name='order_items', on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return '{}'.format(self.id) def get_cost(self): return self.price views.py @login_required def profile(request): user_orders = Order.objects.filter(user=request.user) data = { 'user_orders': user_orders, } return render(request, 'store/main_pages/profile.html', data) Шаблон выведения истории заказов {% for item in user_orders %} {{ item }} {{ item.order.all }} {% endfor %} Profile template admin order panel -
How to get multiple clicks or multiple enter keys in django form?
I have a post form in Django. When this form submits, I want a 2nd submit event not to occur until the result is returned. For this, I added the button disable property after it was clicked. Even if the button is disabled, when the button is pressed repeatedly while the page is loading, or when it is entered, the same actions are recorded in the database. How can I prevent this? This is my HTML form <form action="{% url 'neworder' %}" method="POST"> <!-- <form action="#" method="POST"> --> {% csrf_token %} <div class="form-group"> <label for="username">Kullanıcı Adı</label> <hr> <input type="text" placeholder='Kullanıcı adınız' class="form-control" name="username" id="username" required> <br> <label for="bonustur">Bonus Türü</label> <hr> <select name="orders" id='ordervalue' class="form-control" required> {% for x in orders %} {% if x.status == True %} <option value="{{x.orderid}}" style="font-weight: bolder;">{{x.ordername}}</option> {% endif %} {% endfor %} </select> <br> <button type="submit" class="btn btn-success btn-load form-control" type="submit" id="button"> <span class="d-flex align-items-center"> <span class="flex-grow-1 me-2">Check</span> <span class="spinner-border flex-shrink-0" role="status" style="display: none;"> </span> </span> </button> <!-- <button type="submit" class="btn btn-success form-control" id="button">Talep Et </button> --> </div> </form> The JQuery codes I've tried to prevent this multiple clicks <script> jQuery(function($){ $("#button").click(function(){ $.ajax({ type:'POST', success: function(data){ console.log(data); } }).done(function(){ setTimeout(function() { $("#button").prop('disabled', 'true'); $("#button").text('Checking'); $(".spinner-border").css('display', … -
Django broken pipe 56528
enter image description here Can't store data in db using psql please help . Made django project for first time . -
mediafile not working nginx server and aws infrastructure, Django
i have this messege when i click url of the image: this is my log nginx: this is my nginx configuration: this is my route of media file. My settings.py MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' i try show image with: {{MEDIA_URL}}{{instance.image.url}} -
its showing me that "book() got an unexpected keyword argument 'name'"
its showing me that "book() got an unexpected keyword argument 'name' " my views.py def book(request): if request.method=='POST': name=request.POST['name'] email=request.POST['email'] password=request.POST['password'] type=request.POST['r'] ticket_from=request.POST['ticket_from'] ticket_to=request.POST["ticket_to"] dept_date=request.POST['dept_date'] ret_date=request.POST['ret_date'] adults=request.POST['adults'] children=request.POST['childern'] tck=book(name=name,email=email,password=password,type=type,ticket_from=ticket_from,ticket_to=ticket_to,dept_date=dept_date,ret_date=ret_date,adults=adults,children=children) tck.save() return HttpResponse("Booked") else: return render(request,"book.html",) models.py # Create your models here. class book(models.Model): name=models.CharField(max_length=100) email=models.EmailField(max_length=100) password=models.CharField(max_length=100) type=models.CharField(max_length=100) ticket_to=models.CharField(max_length=100) ticket_from=models.CharField(max_length=100) dept_date=models.DateField() ret_date=models.DateField() adults=models.IntegerField() children=models.IntegerField() i dont know what is this error and how can i solve this plzz help me with this -
Why value is not changing in the database using django
I want to insert value in the database from checklist. it print me the value but does't show anything in the database. it's empty. sample output what I'm getting if ISMS(which is on the third place) is checked [00100] the zero changes accordingly but this data is not inserting in the data base below is my code:: Views.py from collections import Counter from .models import details from django.shortcuts import render from .forms import CheckBoxForm # Create your views here. def home(request): return render(request, 'home.html', {"text": "hello home"}) def about(request): return render(request, 'about.html', {"text": "hello about"}) def checkbox(request): if request.method == 'POST': exec_summary = request.POST.get('Executive_summary') scope = request.POST.get('Scope') isms = request.POST.get('ISMS') methodology = request.POST.get('Methodology') recommendation = request.POST.get('Recommendation') print(f'{exec_summary}{scope}{isms}{methodology}{recommendation}') return render(request, 'checkbox.html') def form_checkbox(request): if request.method == 'POST': form = CheckBoxForm(request.POST or None) if form.is_valid(): print(form.cleaned_data) else: form = CheckBoxForm() context = {'form': form} return render(request, 'checkbox.html', context) urls.py: from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home), path('about/', views.about), path('checkbox/', views.checkbox) ] forms.py from django import forms from .models import details class CheckBoxForm(forms.Form): exec_summary = forms.BooleanField(required=False) scope = forms.BooleanField(required=False) isms = forms.BooleanField(required=False) methodology = forms.BooleanField(required=False) recommendation = forms.BooleanField(required=False) class Meta: … -
Image field form not validating
I have this view with two forms. def anunciocreateview(request): anuncio_form = AnuncioForm(request.POST or None) producto_form = ProductoForm(request.POST or None) if request.method == "POST": if all([anuncio_form.is_valid(), producto_form.is_valid(), imagen_form.is_valid()]): anuncio = anuncio_form.save(commit=False) anuncio.anunciante = request.user anuncio.save() producto = producto_form.save(commit=False) producto.anuncio = anuncio producto.save() return HttpResponse(status=204, headers={'HX-Trigger' : 'eventsListChanged'}) else: anuncio_form = AnuncioForm() producto_form = ProductoForm() context = { 'anuncio_form' : anuncio_form, 'producto_form' : producto_form, } return render(request, 'buyandsell/formulario.html', context) This view works OKAY; it allows the user to create instances of both models with the correct relation. I'm trying to add another form for the image of the product. I tried adding this: def anunciocreateview(request): anuncio_form = AnuncioForm(request.POST or None) producto_form = ProductoForm(request.POST or None) imagen_form = ImagenForm(request.POST, request.FILES) if request.method == "POST": if all([anuncio_form.is_valid(), producto_form.is_valid(), imagen_form.is_valid()]): anuncio = anuncio_form.save(commit=False) anuncio.anunciante = request.user anuncio.save() producto = producto_form.save(commit=False) producto.anuncio = anuncio producto.save() imagen = imagen_form.request.FILES.get('imagen') if imagen: Imagen.objects.create(producto=producto, imagen=imagen) return HttpResponse(status=204, headers={'HX-Trigger' : 'eventsListChanged'}) else: anuncio_form = AnuncioForm() producto_form = ProductoForm() imagen_form = ImagenForm() context = { 'anuncio_form' : anuncio_form, 'producto_form' : producto_form, 'imagen_form' : imagen_form } return render(request, 'buyandsell/formulario.html', context) But this happens: 1- The 'Image upload' form field shows error 'This field is required' at the moment of rendering the form. … -
Django Admin - Fill inline field after autocomplete selection
I have a model with an inline model (see screenshot). The user selects a product via autocomplete and I would then like to fill in the purchasing price, that comes from the product. Here are my models. The PoItem-Model: class PoItem(models.Model): po = models.ForeignKey(PurchaseOrder, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True, blank=True) quantity = models.IntegerField() purchasing_price = models.DecimalField(decimal_places=2, max_digits=5, default=0) Here the product model. These ones here are listed in the autocomplete. And the purchasing_price from the product should be listed in purchasing_price field of the inline form, once a product has been selected via autocomplete class Product(models.Model): sku = models.CharField(primary_key=True, max_length=40, unique=True) name = models.CharField(max_length=250) purchasing_price = models.FloatField(null=True, blank=True) And here is my admin view. I have not listed the PurchaseOrder model as it's of no relevance: @admin.register(PurchaseOrder) class PurchaseOrderAdmin(admin.ModelAdmin): class PoItemInline(admin.TabularInline): model = PoItem fields = ["product", "quantity", "purchasing_price"] extra = 1 autocomplete_fields = ["product"] form = PoItemInlineForm inlines = [PoItemInline] I would need some kind of even that gets triggered once a product has been selected. -
How to achieve Dependent Dropdown between Country and State in Django inside Admin Panel
So i have created a customer portal in django admin panel and i am not using any html because i will use the django default template throughout as of now. But there is a slight issue which i am getting and that is not able to get dependent dropdown between the states and country. Refer this image --> As you can see every city is popping up in the drop down. I want the user to select country and then according to that country states should appear and then finally the user can manually enter the city name which he desires. I have heard something related to ajax (js) in this scenario since i am a newbie i am not really good in javascript so can anyone help me on how to implement it or any other possible solutions for my problem. Thankyou <3 My code: models.py class Country(models.Model): id = models.AutoField(primary_key=True) parent_id = models.IntegerField(null=False) name = models.CharField(null=False, max_length=255) status = models.CharField(null= True, choices=Status_Choices, max_length=11, default="--Select Status--") added_by = models.IntegerField() updated_by = models.IntegerField(null=True) created_on = models.CharField(default=get_current_datetime_str , max_length=255) updated_on = models.CharField(default=get_current_datetime_str, max_length=255) def __str__(self): return self.name class State(models.Model): Country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(null=False, max_length=255) status = models.CharField(null= True, … -
how to update a document then find the updated values in one mongodb using django?
I'm trying to update some values to a document in a collection using dbconn.collectionName.update_one( {'_id': ObjectId('6396c654efd251498ea4ebbc')}, {'$addToSet': { 'updateHistory': { "key":"Text", "key":"date" "key":ObjectId("633456783er5t672342134") } } }, {'$set': { "key":"Text", "key":ObjectId("633456783er5t672342134") } } ) so what I'm trying to achieve is get the updated values from the same collection with single query after its updated, is that possible? I've tried findAndModify() & findOneAndUpdate() -
Update single row of table in template page using ajax in Django
I am working on Django project and I have no idea of ajax that how to implement it. The scenario is my db contains a table name "demo" which contains the column stat_id. My database contains the following details: table name = demo id int primary key NOT NULL, stat_id int(11) NOT NULL #value is 1 Now, the scenario is that I am getting the stat_id value from database and its purpose to show the running and complete button. If python script is running then it will display the running button and if python script has executed it will display the completed button. status.html: <td> <form action = "/modules" method="get"> {% if status == 1 %} {% csrf_token %} <button link="submit" class="btn btn-default btn-sm"> <span class="badge badge-dot mr-4"> <i class="bg-success"></i>Completed</button> </form> {% else %} <button type="button" class="btn btn-default btn-sm"> <span class="badge badge-dot mr-4"> <i class="bg-warning"></i>Running</button> {% endif %} views.py: def process(request): hash_id = request.session.get('hash_id') print(hash_id) check = request.session.pop('check_status',) if hash_id and check: stat = status_mod.objects.filter(hash_id = hash_id).order_by('-id').first() if stat: stat = stat.stat_id print(stat) return render(request, 'enroll/status.html', {'status': stat}) urls.py: path('status', views.process, name='process') models.py: class status_mod(models.Model): id = models.BigIntegerField(primary_key=True) stat_id = models.BigIntegerField() class Meta: db_table = "demo" jquery / ajax in …