Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Bootstrap 5 - Navbar - Logo/Brand Text Left - Menu Center - Search Right
I am trying to make a Navbar in Bootstrap 5. I would like to have the Logo (In my case this is just some fancy text) on the left. I would then like the menu centered and my search field on the right. The issue I seem to be having is when I have managed to get them lined up like this, the menu is going in the center of the search and logo divs, which due to logo size etc hasn't necessarily been the middle of my screen like I want. I have been at it for days trying different things on her but just can't seem to get it right. I also want the mobile menu to collapse and include the search. The mobile menu should then have the logo aligned in the center and the collapse button just below it also centered. The latest code I have tried is this: index.html: {% load static %} <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>{% block title %}{% endblock %}Life With Vicky</title> <meta name="description" content="{% block meta_description %}{%endblock %}"> {% block canonical %}{%endblock %} {% block opengraph %}{%endblock %} <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous"> <link … -
How to manage session with 3rd party API in Django?
Context: I have a Django based application. This application has various REST API endpoints where users can gather data. Some of this data needs to be pulled from a third-party API. This external API uses basic authentication. In order to fetch this data, I have the following code implemented in my endpoint logic. def metadata(jira_key: str, format=None): username = "example" password = "example" try: print(f"fetching {jira_key} with '{username}' credentials") url = f"https://external.api.com/issue/{jira_key}" session = requests.Session() session.auth = username, password headers = {'Content-Type': 'application/json'} response = session.get( url, headers=headers) print(f"response: {response.status_code}") return response except Exception as e: message = {"error": "Uncaught error", "message": str(e)} return message Long story short; it works! This endpoint is essentially just a proxy for another API. This is done for security purposes. However, I have been experiencing lock-outs where permission for the service account needs to be reinstated periodically... I suspect the session is being generated every time the endpoint is hit. So my question is this: How can I implement a persisted request.Session() with basic auth that is established at build time, and reused for each requests? Thanks for your help in advance! :) -
Timeout error in django send_mail program
I am doing a send_mail function in django and connected mysql database with it to store the name and subject values. I am using the smtp backend server to connect the mail and django. The port used is 587. This is my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mail_test', 'USER': 'root', 'PASSWORD': '', 'HOST':'localhost', 'PORT':'3306', 'OPTIONS':{ 'init_command':"SET sql_mode='STRICT_TRANS_TABLES'" } } } ---- DEFAULT_AUTO_FIELD = 'django.db.models.AutoField' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'swarai.bot@gmail.com' EMAIL_HOST_PASSWORD = 'pfxbswfjgligavgb' ** This is my views.py** from django.views.generic import FormView, TemplateView from .forms import EmailForm from django.urls import reverse_lazy from mailapp.models import Email from django.shortcuts import render class MailView(FormView): template_name = 'index.html' form_class = EmailForm success_url = reverse_lazy('mailapp:success') def form_valid(self, form): # Calls the custom send method form.send() return super().form_valid(form) def registered(request): name = request.POST['name'] email = request.POST['email'] inquiry = request.POST['inquiry'] message = request.POST['message'] person = Email(name=name, email=email, inquiry=inquiry, message=message) person.save() return render(request, 'success.html') class MailSuccessView(TemplateView): template_name = 'success.html' I am getting timeout error whenever I submit the page. I tried to add the port 587 using control panel. But then also, I am getting the same error. I don't know whether this error is … -
django post request: Forbidden (CSRF token missing.): /categories
In my file view.py I want to write a class based on View with get and post methods for API. Get is already written, it works. There was a problem with the post: Code of this class: class CategoryListView(View): def get(self, request): if not check_correct_api_secret(request): return HttpResponseForbidden('Unknown API key') query_set = Category.objects.all() query_params = request.GET query_set = paginate(query_params, query_set) items_data = serialize_category_list(request, query_set) return JsonResponse(items_data, safe=False) # Method code is written for example, just to see some kind of reaction to the post request def post(self, request): query_params = request.POST name = query_params.get('name') Category.objects.create(name=name) return HttpResponse(201) I try send post request: /categories?name=Category6 (For example) And I get error: Forbidden (CSRF token missing.): /categories [21/Jun/2022 16:21:26] "POST /categories?name=Category777 HTTP/1.1" 403 2506 My urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('categories', CategoryListView.as_view()), ] -
“non_field_errors”: [ “Invalid data. Expected a dictionary, but got QuerySet.” ] problem with serializer or model from djongo
I've recently started to learn django. And at this time i'm working on integrating mongoDB with Django using djongo driver. I've created a model for saving and mapping my data objects to mongoDB but i'm lacking knowledge about implementing serializers and at this stage i'm encountering one situation which i've been unable to resolve since 2 days so please throw some light and help me implement it. the error message from django REST framework api models.py from djongo import models # Create your models here. class OrderItem(models.Model): itemDescription = models.TextField(name = "itemDescription") itemQuantity = models.FloatField(name = "itemQuantity") itemPrice = models.FloatField(name = "itemPrice") class Meta: abstract = True class Order(models.Model): email = models.EmailField(primary_key = True, name = "email") customerName = models.CharField(max_length=30, help_text="Enter Customer Name", name = "customerName") customerAddress = models.TextField(help_text="Enter customer's Address", name = "customerAddress") orderItems = models.ArrayField( model_container = OrderItem, ) objects = models.DjongoManager() serializers.py from .models import Order, OrderItem from rest_framework.serializers import ModelSerializer class OrderItemsSerializer(ModelSerializer): class Meta: model = OrderItem fields = '__all__' class OrderSerializer(ModelSerializer): orderItems = OrderItemsSerializer(many=True) class Meta: model = Order fields = "__all__" views.py @api_view(['GET']) def getOrders(request): orders = Order.objects.values() serializer = OrderSerializer(data = orders) if serializer.is_valid(): print("Valid") return Response(data = serializer.data) else: print("invalid") print(serializer.errors) return … -
Nested Serializers with different queryset
How to create a nested serializer with it's own queryset? In the following example I would like to replace an '@api_view' function with a class based view with serializers. Simplified, I have the following code: models.py class Klass(models.Model): name = models.TextField() class Pupils(models.Model): name = models.TextField() klass = models.ForeignKey(Klass) class Chapter(models.Model): """A Chapter in a school book.""" name = models.TextField() class TestResult(models.Model): """TestResults for a Chapter.""" pupil = models.ForeignKey(Pupil) chapter = models.ForeignKey(Chapter) score = models.IntegerField() view.py @api_view def testresults(request, klass_id, chapter_id): pupils = Pupils.objects.filter(klas__id=klass_id) tests = Tests.objects.filter(chapter__id=chapter_id) ret_val = [] for pupil in pupils: pu = { "name": pupil.name, "tests": [{"score": test.score, "chapter": test.chapter.name} for test in tests.filter(pupil=pupil)] } ret_val.append(pu) return Response({"pupils": ret_val}) url /api/testresult/<klass_id>/<chapter_id>/ -
IIS can not access newly added files in a django project
In a django project that is served by IIS (windows), i added a local file, test.py. The project ran perfectly before and still runs perfect on localhost, however IIS appears to not recognize the new test.py file. It appears IIS access to this file fails, even if the users IUSR and IIS_USRS have full access (same as for all other files in the folder). I get below error message, and somethimes also the same but "No module named 'app.test'. Removing the "import app.test as test" in views.py solves the issue. Suprisingly the "import app.oldFile as oldFile" works without issue. In my views.py, i import the python scripts like this import app.oldFile as oldFile import app.test as test My django project has the structure: djangoRest -app --__init__.py --views.py --oldFile.py --test.py -djangoRest --__init__.py --settings.py --urls.py --wsgi.py -
How to know if which selected in django template select?
In my django templates how can I know which select option is selected? <select id="platformid" name="platform"> {% for x in list %} <option value="{{x.company}}">{{x.company}}</option> {% endfor %} </select> -
Django POST request returns NONE
so ive been serching for a solution for about a week now I just need the data from a hidden label within a form witch should be no problem but instead of the data from the label i just get 'NONE' Template (form): {% for Gerecht in Gerechten %} <form method="POST"> {% csrf_token %} </section> <section class="u-clearfix u-custom-color-2 u-valign-middle u-section-2" id="sec-a9e5"> <div class="u-clearfix u-gutter-0 u-layout-wrap u-layout-wrap-1"> <div class="u-layout" style=""> <div class="u-layout-row" style=""> <div class="u-align-left u-container-style u-image u-layout-cell u-left-cell u-shading u-size-30 u-size-xs-60 u-image-1" src="" data-image-width="4880" data-image-height="3253" style=" background-image: linear-gradient(0deg, rgba(0,0,0,0.25), rgba(0,0,0,0.25)), url('{% static '/img/{{ Gerecht.afbeelding }}' %}')"> <div class="u-container-layout u-container-layout-1" src=""></div> </div> <div class="u-align-left u-container-style u-custom-color-1 u-layout-cell u-right-cell u-size-30 u-size-xs-60 u-layout-cell-2"> <div class="u-container-layout u-container-layout-2"> <h2 class="u-text u-text-default u-text-white u-text-1"> {{ Gerecht.naam }}</h2> <p class="u-text u-text-default u-text-white u-text-2">Duur: {{ Gerecht.duur }} u </p> <input type="submit" value="ga naar gerecht" class="u-active-custom-color-3 u-align-left u-border-1 u-border-active-custom-color-3 u-border-hover-custom-color-3 u-border-white u-btn u-btn-round u-button-style u-hover-custom-color-3 u-none u-radius-12 u-text-active-white u-text-hover-white u-btn-2" name="btnZieRecept"> <label name="id" style="display: none;" value="{{ Gerecht.id }}">{{ Gerecht.id }}</label> </div> </div> </div> </div> </div> </section> </form> {% endfor %} My views.py: if request.POST.get('btnZieRecept'): PK = request.POST.get('id') logging.basicConfig(level=logging.NOTSET) logging.debug(request.POST.get('id')) return redirect('GerechtPreview', PK=PK) So here PK=None and i dont know why def GerechtPreview(request, PK): obj = Gerecht.objects.get(pk=PK) ingList=[] for f … -
Django: How to change the value on a model's field within a property on the model
I would like to change the value of a model field within a property set on the model. Let's say we have the model and the following properties: class Rider(models.Model): booking = models.BooleanField(default=True) cancel = models.BooleanField(default_True) _disabled_notifications = JSONField() @property def disabled_notification(self): return json.loads(self._disabled_notifications @disabled_notifications.setter def disabled_notifications(self, value) try: field = self._meta.get_field(value) except FieldDoesNotExist as e: raise e In this case, field would return an Options object. How do I use this to change the value on the field? -
How to test Stripe `SignatureVerificationError` in Python
For python, the standard stripe webhook code example includes: event = None try: event = stripe.Webhook.construct_event(payload, sig_header, endpoint_secret) except ValueError as e: logger.error(f"*** Stripe invalid payload: {e = }") return HttpResponse(status=400) except stripe.error.SignatureVerificationError as e: logger.error(f"*** Stripe invalid signature: {e = }") return HttpResponse(status=400) I've tried to test this with the following test that inherits from Django testcase: class TestStripeWebhookView(TestCase): @mock.patch("logging.Logger.error") @mock.patch("lettergun.apps.payments.views.create_order") @mock.patch("lettergun.apps.payments.views.stripe") def test_signature_verification_error(self, stripe, create_order, error): stripe.Webhook.construct_event.side_effect = SignatureVerificationError data = { "type": "placeholder", } response = self.client.get( reverse("payments:stripe_webhook"), data, HTTP_ACCEPT="application/json", HTTP_STRIPE_SIGNATURE='placeholder_signature"}', ) error.assert_called_with(f"*** Stripe invalid signature: e = an error message") assert not create_order.called assert response.status_code == 400 This produces the following error which I dont understand: > except stripe.error.SignatureVerificationError as e: E TypeError: catching classes that do not inherit from BaseException is not allowed How can I test that the signature verification error will have the expected effects? -
Change model rendered form select/option element into multi-select checkboxes with Django
I need to change two form fields (now select/option) into multi-choice checkboxes in a form that is rendered from the model. Despite carefully reading the Django docs I don't get it displayed, i.e nothing happens. What do I need to do in models.py to render the checkboxes? (For simplicity, I only display the code for one field) So far in form.py: class CreateVariantForm(ModelForm): class Meta: model = VariantView fields = '__all__' suitable_for = forms.MultipleChoiceField(choices=VariantView.SuitableForProduct.choices, widget=forms.CheckboxSelectMultiple) In models.py: class VariantView(models.Model): class SuitableForProduct(models.TextChoices): JEWELLERY = "Jewellery", _("Jewellery") ACCESSORIES = "Accessories", _("Accessories") COSMETICSHYGIENE = "Cosmetics & Hygiene", _("Cosmetics & Hygiene") ELECTRONICSGADGETS = "Electronics & Gadgets", _("Electronics & Gadgets") suitable_for_product = models.CharField(max_length=255, choices=SuitableForProduct.choices, null=True, blank=True ) class Meta: managed = False db_table = "variant_view" In views.py: class ProductUpdate(LoginRequiredMixin, UpdateView): login_url = "/" model = VariantView template_name = "searchapp/product_update_form.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["suitable_for_product"] = SuitableForProduct.objects.values_list( "suitable_for", flat=True ) return context def get_success_url(self): return reverse_lazy("listvariants", args=[self.object.product_group_id])`` ``` -
csrf_token verification failed?
I am a beginner and searched a lot about it but do not got any thing please explain why this error is coming. I have used this code from here: JavaScript post request like a form submit Error is coming from the following code in my html template in under script tag: This code is from Davidson Lima comment: post("{% url 'savep' %}", {name: user_name, pass: user_pass, csrfmiddlewaretoken: $("csrf_token").val()}); Here is the code of views.py def save_login(request): x = request.POST['user'] y = request.POST['pass'] member = credentials(user_name=x, user_pass=y) member.save() Error: Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token from POST has incorrect length. -
Django foreignkey between two databases
I'm looking to connect two SQLite tables together (oh dear). I found this solution : How to use django models with foreign keys in different DBs? , I adapted it to my models and my code (I think). I have no bad answers from django. However, I would like to modify the entry with the admin view of django, and when I try to add the entry with the foreign key of another database, I get this answer: Exception Type: OperationalError at /admin/users/character/add/ Exception Value: no such table: books How to adapt to fix it? models database default from django.db import models from users.related import SpanningForeignKey from books.models import Books class Character(models.Model): last_name = models.fields.CharField(max_length=100) first_name = models.fields.CharField(max_length=100) book = SpanningForeignKey('books.Books', null=True, on_delete=models.SET_NULL) def __str__(self): return f'{self.first_name} {self.last_name}' models external database from django.db import models # Create your models here. class Books(models.Model): title = models.TextField() sort = models.TextField(blank=True, null=True) timestamp = models.TextField(blank=True, null=True) # This field type is a guess. pubdate = models.TextField(blank=True, null=True) # This field type is a guess. series_index = models.FloatField() author_sort = models.TextField(blank=True, null=True) isbn = models.TextField(blank=True, null=True) lccn = models.TextField(blank=True, null=True) path = models.TextField() flags = models.IntegerField() uuid = models.TextField(blank=True, null=True) has_cover = models.BooleanField(blank=True, null=True) … -
Django REST API: Invalid data. Expected a dictionary, but got User
I want to design a REST API where user can submit a new car record using POST request. The user is automatically should be set as creator. Under my models.py I have: class CarRecord(models.Model): type = models.CharField(max_length=50) license = models.CharField(max_length=50) creator = models.ForeignKey(User,on_delete=models.DO_NOTHING) Under my serializers.py I have: class UserSerializer(serializers.ModelSerializer): username = serializers.CharField(max_length=50) class Meta: model = User fields = ['username'] class CarRecordSerializer(serializers.ModelSerializer): type = serializers.CharField(max_length=50) license = serializers.CharField(max_length=50) creator = UserSerializer() class Meta: model = CarRecord fields = ('__all__') And In the post method I have: class CarRecordViews(APIView): def post(self, request): user = request.user if not user.is_authenticated: user = authenticate(username=request.data['username'], password=request.data['password']) if user is None: return Response(data={"error": "bad username/password"}, status=status.HTTP_401_UNAUTHORIZED) data = { 'type': request.data['type'], 'license': request.data['license'], 'creator': user } serializer = CarRecordSerializer(data=data) serializer.is_valid(raise_exception=True) return Response({"message": "success"}, status=status.HTTP_201_CREATED) But I get: { "creator": { "non_field_errors": [ "Invalid data. Expected a dictionary, but got User." ] } } I want to keep the user as the creator. I'm not sure I fully understand how serializers work but I believe the problem is in that file. Have can I make it work? -
Get Dn from an AD, using LDAP protocol on python without connection
I try ot make a Django app using connection by ldap. To test the connection you need to use <ldapInstance>.simple_bind_s(User, Password) where User is a DN : CN=me,OU=other,DC=com (for exemple) So i try to get this DN by a function using : <ldapInstance>.search_s(paramers...) and return this error : info: 0002020: Operation unavailable without authentification The problem is, if i want DN, i need connection using DN for connection. Someone have an idea ? -
Django Upload File, Analyise Conents and write to DB or update form
I'm pretty new to Django, Trying to get my grips with it, and expand what I think its capable of doing, and maybe one of you more intelligent people here can point me in the right direction. I'm basically trying to build a system similar to a so called "Asset Management" system, to track software version of a product, so when an engineer updates the software version, they run a script which gathers all the information (Version, Install date, Hardware etc), which is stored in a .txt file, The engineer then comes back to the website and upload this .txt file for that customer, and it automatically updates the fields in the form, or directly to the database. While, I've search a bit on here for concepts, I haven't been able to find something similar (Maybe my search terms aren't correct?), and wanted to ask if anyone knows, what I'm doing is even feasible, or am I lost down the rabbit hole of limitations :) Maybe its not do-able within Django, Any suggestions on how I should approach such a problem would be greatly appreciated. -
how can I count data from foreign key field in Django template?
models.py: class Region(models.Model): city = models.CharField(max_length=64) class Properties(models.Model): title = models.CharField(max_length=200) Region = models.ForeignKey(Region, related_name='Region', on_delete=models.Cascade) how can i count all properties which have the same region ? -
Django import-export library ForeignKey error (IntegrityError: FOREIGN KEY constraint failed in django)
First of all please sorry for my English. )) So I have a problem with Django import-export library when I try to import data from csv/xls/xlsx files to the Django application DB. How it looks like. Here is my models.py: class Department(models.Model): department_name = models.CharField(max_length = 50, default = '', verbose_name = 'Подразделение') def __str__(self): return f'{self.department_name}' class ITHardware(models.Model): it_hardware_model = models.CharField(max_length = 100) it_hardware_serial_number = models.CharField(max_length = 100, blank = True, default = '') it_hardware_department = models.ForeignKey(Department, related_name = 'department', on_delete = models.SET_NULL, default = '', null = True, blank = True, db_constraint=False) admin.py: @admin.register(Department) class DepartmentAdmin(admin.ModelAdmin): list_display = ('department_name', ) actions = [dublicate_object] @admin.register(ITHardwareManufacturer) class ITHardwareManufacturerAdmin(admin.ModelAdmin): list_display = ('manufacturer', ) actions = [dublicate_object] class ITHardwareImportExportAdmin(ImportExportModelAdmin): resource_class = ITHardwareResource list_display = ['id', 'it_hardware_manufacturer', 'it_hardware_model', 'it_hardware_serial_number', 'it_hardware_department'] actions = [dublicate_object] resource.py: class ITHardwareResource(resources.ModelResource): it_hardware_department = fields.Field( column_name = 'it_hardware_department', attribute = 'ITHardware.it_hardware_department', widget = widgets.ForeignKeyWidget(Department, field = 'department_name')) class Meta(): model = ITHardware fields = ( 'id', 'it_hardware_model', 'it_hardware_serial_number', 'it_hardware_department', ) export_order = ( 'id', 'it_hardware_model', 'it_hardware_serial_number', 'it_hardware_department', ) import file: import file If I try to import data from file, I get such error: String number: 1 - ITHardwareManufacturer matching query does not exist. None, Canon, BX500CI, 5B1837T00976, Office_1, … -
How to display multiple django database models in a flex box row?
So just to give some information, I know how flexbox works and sorta know how django works and have displayed django database models on a page before already, using a loop. The issue I've encountered is I want to have multiple (three) of these models on a row kinda like if I used a flex box with three divs inside except because of the way the loop is running all three divs are the same. Any ideas on how to change the code for the divs to all be different models? Here is my code : Here is my item-store.html (Html Page to display the items) : {% for item in items %} <div class="triple-item-container"> <div class="single-item-container"> <div><p>{{item.name}}</p></div> <div><p>{{item.details}}</p></div> </div> <div class="single-item-container"> <div><p>{{item.name}}</p></div> <div><p>{{item.details}}</p></div> </div> <div class="single-item-container"> <div><p>{{item.name}}</p></div> <div><p>{{item.details}}</p></div> </div> </div> {% endfor %} Here is my item-store.css (Css Page linked to the Html Page) : .triple-item-container{ margin-top: 300px; height: 200px; display: flex; flex-direction: row; justify-content: space-around; } .single-item-container{ padding: 10px; background-color: rgb(226, 215, 113); } Here is my models.py in case you need it : class item(models.Model): name = models.CharField(max_length=100, blank=False, null=False) details = models.CharField(max_length=1000, blank=True, null=True) price = models.DecimalField(blank=False, null=False, decimal_places=2, max_digits=20) tag_choices = ( ('bakery', 'bakery'), ('meat&seafood', … -
почему сериализатор меняет имя автора , на его айди? [closed]
Comments models.py class Comments(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Posts, on_delete=models.CASCADE) text = models.CharField(max_length=500) created = models.DateTimeField(auto_now=True) class META: fields = ['author', 'post', 'text', 'created']` user models.py class User(AbstractUser): status = models.CharField(max_length=120, default='it\s a default user status', null=False) avatar = models.ImageField(upload_to='Network_/static/avatar/') views.py def get_post(self): post = Posts.objects.get(id=self.GET.get('post_id')) post_likes_len = len(Like.objects.filter(product=post)) like_icon = "/static/image/likeHearthicon.png" if Like.check_user_liked(self, user=self.user, post=post): like_icon = "/static/image/likeHearthicon_after.png" post_comments = Comments.objects.filter(post=post) return JsonResponse({ 'post': serializers.serialize('json', [post]), 'Likes':post_likes_len, 'like_icon': like_icon, 'comments': serializers.serialize('json', post_comments) }, safe=False ) Я новичок в dango, и не совсем понимаю что , и из-за чего меняет имя автора комментария на его айди. до этого действия (serializers.serialize('json', post_comments)) все выводиться нормально : 'Test_user_3' но после сериализации вместо 'Test_user_3' я получаю '3' то есть айди может кто-нибудь обьяснить , или хотя бы кинуть ссылку для того чтобы моя ветряная башка хоть что-то поняла -
Django : Dynamically set dropdown options based on other dropdown selection in Django Model Forms
This is a common scenario in frontend where we want a dropdown options set with respect to another selection in another dropdown, but not getting a solution in django admin forms Scenario : django model: class CompanyEmployee(): """ An Emailed Report """ company = models.ForeignKey(Company, on_delete=models.CASCADE, ) employee = models.ManyToManyField(Employee, blank=True, verbose_name='Employes',) class Meta: unique_together = ( ('company', 'name'), ) so in CompanyEmailAdminForm company is in list_filter and Employee as filter_horizontal, that means company is a dropdown and employee as filter with multiple choice. The queryset for employee widget if instance.pk: self.fields['employee'].queryset =Employee.objects.filter(company=instance.company) else: self.fields['employee'].queryset =Employee.objects.all() Company and Employee have a relation. So from company I can get the related Employee records. The issue is in add form where I don't have a saved instance. My requirement is when I select a company say 'ABC' I should get only records related to 'ABC' in the Employee filter. If onChange i can get the value back in the form I can re-evaluate the employee queryset. With django.JQuery the values in the employee section is not remaining permanently. -
How to get "captured values" from a url in get_absolute_url model in django
I have this url: path('<slug:slug>/<slug:product_slug>_<int:pk>/', ProductDetailView.as_view(), name='detail'), and I need access to < slug:slug > in product's get_absolute_url, this slug can be any of user's slug, is not from products. Is for generate the products breadcrumb urls like this: /user-slug/product-slug_product-id/ def get_relative_url(self): return reverse('custom_catalogue:detail', kwargs={ slug: kwargs['slug']??, 'product_slug': self.slug, 'pk': self.id}) any help I will appreciate -
Django ORM: calculation only inside databse-query possible?
I have rather simple dataset that's containing the following data: id | aqi | date | state_name 1 | 17 | 2020-01-01 | California 2 | 54 | 2020-01-02 | California 3 | 37 | 2020-01-03 | California 4 | 29 | 2020-01-04 | California What I'm trying to achieve is the average aqi (air-quality-index) from april 2022 minus the average aqi from april 2021, without using multiple queries. Is this even possible or should I use two queries and compare them manually? From my understanding, I should use the Q-Expression to filter the correct dates, correct? AirQuality.objects.filter(Q(date__range=['2021-04-01', '2021-04-30']) & Q('2022-04-01', '2022-04-30')) Thanks for your help and have a great day! -
Why only 1 value is bound?
The meaning of the program is to select analogues from the list and link them. I always bind only 1 value (to itself). How to fix it My view: def editpart(request, id, **kwargs): if request.method == 'POST': part.name = request.POST.get("name") part.description = request.POST.get("description") analogs = Part.objects.all() for analogs_zap in analogs: zap = analogs_zap.analog part.analog.add(part.id) My model: class Part(models.Model): name = models.CharField('Название', max_length=100) analog = models.ManyToManyField('self', blank=True, related_name='AnalogParts')