Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django 2.2.5 product not displaying in shopping cart
I am creating a e-commerce site using django 2.2.5. I've been following a tutorial on udemy where the instructor is moving at a rapid pace and he's using an older version of django i am continuously trying to pause just to ensure my code is correctly (it's AWFUL). I am now creating a shopping cart. The price is updating correctly but the product(s) price and description are not displaying. I've back tracked checked all the videos leading up to this part of the project but i can't seem to find what i've done incorrectly, so i've decided to come here for a second / third set of eyes that maybe able to see why the product(s) price and description are not displaying. cart (cart.html): I have a forloop.counter that is looping through the products and is suppose to display the price and description of products added to the cart. {% extends 'base.html' %} {% block content %} {% load staticfiles %} <div class="pb-5"> <div class="container"> <div class="row"> <div class="col-lg-12 p-5 bg-white rounded shadow-sm mb-5"> <!-- Shopping cart table --> <div class="table-responsive"> {% if cart.product.exists %} <table class="table"> <thead> <tr> <th scope="col" class="border-0 bg-light"> <div class="p-2 px-3 text-uppercase">Product</div> </th> <th scope="col" … -
Django app keeps crashing after an exception until it is restarted
I am using Django + uWSGI + nginx to serve an application. All requests from the front end are post requests. The Behaviour: In the code snippet below, the function, convert_data, connects to a database and converts request into resp. class ConvertDataView(View): def post(self, *args, **kwargs): request = json.loads(args[0].body.decode()) resp = api_utils.convert_data(request) if resp: return JsonResponse(resp, safe=False) return JsonResponse({}, status=404) When ever the inputs contains invalid characters such as \, ', " etc, convert_data raises an exception. This varies from database to database but it is form of "Query is invalid.". The Problem: All subsequent queries to this core/thread continue to fail, even if the input is correct and does NOT contain any invalid characters. This behavior causes the app to be unstable and serve the information when the request goes to another core/thread but fail when it comes to this "corrupted core/thread". This error will continue to persist until the uwsgi server is restarted. After the uwsgi server is restarted, the app acts normal again. Things that seem to work: If I perform exception handling in ConvertDataView, this issue seems to remain. However, it seems that if I perform my exception handling in convert_data and always send back a … -
How to display custom form in django-allauth's social account sign up flow
I am trying to achieve all these together: A. New users can sign up with or without using facebook. B. They will all be presented with a form to fill out additional user information as part of the sign up flow. C. New accounts will by default be inactive. Admins will need the additional user information when they manually activate (or delete) accounts. I achieved A using django-allauth social accounts. I achieved C by adding a listener to django.db.models.signals.pre_save and setting user.active = False I partly achieved B by defining a custom ACCOUNT_SIGNUP_FORM_CLASS in settings.py. However this only works for local "non-social" accounts as far as I can tell, since social logins seem to skip this form. My problem is that when someone signs up with an allauth social account they don't have the chance to provide additional information since their account will be created without first displaying my custom sign up form. Furthermore since all new accounts are automatically saved as inactive and that additional information is needed in order for admins to activate them I can't simply add that form to a "first time login flow" (note: it's not possible to log in to inactive accounts). One way … -
How to access Detail page in Dango Rest Framework
I am new to Django Rest Framework and I have ONE question: What is the equivalent to use get_absolute_urland get_object_or_404(model, id=id) to access a DETAIL page from a LIST page with django rest framework??? While reading the official documentation, I have the sense that HyperlinkedModelSerializer could help me achieve it but when I try to access the url : http://127.0.0.1:8000/ it crashes the app with the message below: Could not resolve URL for hyperlinked relationship using view name "post-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. (It crashes because I use URL in Serializer fields, when I use just id it works fine but unable to achieve 1/) I have the built the endpoint below: models class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=50) body = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title Serializers class PostSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Post fields = ('url', 'author', 'title', 'body', 'company') URLS from django.urls import path, include from .views import ( PostList, PostDetail, UserList ) from . import views app_name = 'blog' urlpatterns = [ path('', PostList.as_view()), path('<int:pk>/', PostDetail.as_view()), ] VIEWS class PostList(generics.ListCreateAPIView): permission_classes … -
Django: I have an object A with FK on B. How can I display the columns from B in a dropdown in the form of A?
I am getting the error "Unknown field(s) (topic, subject) specified for Session". I am trying to build a drop down for subject and topic in my sessionForm. My model is below: class Subject(models.Model): name = models.CharField(max_length = 30, primary_key = True) def __str__(self): return self.name class Meta: db_table = 'subjects' class Module(models.Model): topic = models.CharField(max_length = 200) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) def __str__(self): return self.topic + ' in ' + self.subject.name class Meta: db_table = 'modules' class Session(models.Model): grade_level = models.CharField(max_length = 30) num_students = models.IntegerField(default=0) session_dt = models.DateTimeField() module = models.ForeignKey(Module, on_delete=models.CASCADE) @property def subject(self): return self.module.subject def topic(self): return self.module.topic def __str__(self): return self.module.topic + ' on ' + self.session_dt class Meta: db_table = 'sessions' My forms.py is class SessionForm(forms.ModelForm): class Meta: model = Session fields = ['subject', 'topic', 'session_dt', 'grade_level', 'num_students'] I am new to Django and Python. I already looked at Vitor Freitas article on Dropdown list. -
I want to get the value in td with jquery No output as a result of the alert Can you see where the wrong part is?
When the button is clicked <button type="button" class="plus_btn_for_user btn btn-outline-success" data-user_pk="{{u.pk}}" data-user_id="{{request.user}}"> <img src="{% static 'icon/plus.png' %}" alt=""> </button> I wanted to get the count number in td <td id="skill_note_point"> {{ u.recommandationuseraboutskillnote_set.count }} </td> I did this with jQuery const point = $(this).parent().find("#skill_note_point").text(); alert(point) There is no output alert(point) Is the jquery syntax wrong? text, val, html all did not work Is the selector wrong? I can't find the wrong part text, val, html all did not work Is the selector wrong? I can't find the wrong part Thanks for telling me what's wrong ^^; total code {% if user_list.exists %} {% for u in user_list %} <tr> <td>{{forloop.counter}}</td> <td id=user_name_{{u.id}}>{{u.username}}</td> <td> <input type="text" class="shortcut_subject_input_{{u.id}} form-control" value="{{u.profile.subject_of_memo}}"> {% if u.username == request.user.username %} <a href="" class="btn btn-outline-warning btn-sm update_memo_subject_btn" data-id={{u.id}}>수정</a> {% else %} {% endif %} </td> <td> <a href="" class="btn btn-outline-info move_to_user_btn btn-sm" id={{u.id}}>이동</a> </td> <td> <a href="" class="btn btn-outline-info btn-sm copy_to_me_from_user_id_btn" id={{u.username}}>copy_to_me</a> </td> <td> <button type="button" class="plus_btn_for_user btn btn-outline-success" data-user_pk="{{u.pk}}" data-user_id="{{request.user}}"> <img src="{% static 'icon/plus.png' %}" alt=""> </button> </td> <td id="skill_note_point"> {{ u.recommandationuseraboutskillnote_set.count }} </td> </tr> {% endfor %} {% else %} -
Saving GET parameter with User Profile in Django AllAuth
Users come to my site through a referral at example.com/accounts/signup/?ref=123. I use Django AllAuth to sign up users. I would like to save the referral code with their profile. It appears my options for this are: Edit the allauth signup view directly to allow this referral field to be saved Pass the ?ref=123 parameter to the next view after signup so that I can save it to the user profile in that view Create a session variable that gets remembered to the next view after signup so that I can save it to the user profile in that view How can I save the GET parameter to my user profile? Is there something that I can do to subclass the SignupView to save the data (option 3)? from allauth.account.views import SignupView class MySignupView(SignupView): ref = request.GET.get('ref') request.session['ref'] = ref Or is there a way that I can pass it in the form submit? (option 2) <form id="signup_form" method="post" action="{% url 'account_signup' %}?ref={{ request.GET.ref }}"> The page seems to be redirecting in more ways than I understand, so I am not able to retain the get parameters. -
Django how to detect/determine form FileField in template
I am trying to render customized base template for form view on my custom CBV approach Here i am looping through form visible fields, I am able to detect form choicefield/multiplechoicefied type as {% if field.field.widget.input_type == 'select' %} >my html stuffs {% endif %} In similar manner i need to detect form field FileField or ImageField In addition to this also I need to detect and differentiate form Fields ChoiceField and MultipleChoiceFild standalone to finalize my base form-view base template Thank you in advance -
Remove default select box option without JavaScript
I have 'country' CharField with choices on my custom User model, like this: from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): address = models.CharField(max_length=200) address_number = models.CharField(max_length=20) phone = models.CharField(max_length=20) COUNTRY_CHOICES = [ ('US', 'United States'), ('UK', 'United Kingdom'), ('CA', 'Canada'), ('AUS', 'Australia'), ] country = models.CharField(max_length=30, choices=COUNTRY_CHOICES) ...and I'm using UserCreationForm, like this: from django import forms from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm class RegistrationForm(UserCreationForm): class Meta: model = get_user_model() fields = ( 'username', 'email', 'first_name', 'last_name', 'address', 'address_number', 'phone', 'country' ) I'm manually rendering form fields in my template, however the country field is rendered as a select box with one extra option: <option value="" selected="">---------</option> How can I remove that option and have my first option (in this case US) be selected as default? I'm trying to do it proper Django way without JavaScript. -
Conditionally prevent Django join with chained serializers
I have a serializer, requirementsSerializer, that fetches two chained tables, comments and relatedfiles. In my views.py, I know how to conditionally filter for the related tables if the user is logged in. What I am confused about, is how to exclude/prevent the chaining/joining if a user is NOT logged in. Right now, it returns the entire set of relatedfiles, for all users, if the user is not logged in, which is obviously a security issue. I know I could make a second serializer that doesn't join the other tables, but that does not seem efficient or clean. // serializers.py class RequirementsSerializer(serializers.ModelSerializer): relatedfiles_set = RelatedFileSerializer(many=True, read_only=True) comments_set = CommentsSerializer(many=True, read_only=True) class Meta: model = Controls fields = ('id', 'sorting_id', 'relatedfiles_set', 'comments_set', 'requirement', 'requirement_section', 'requirement_subsection', 'requirement_version') // views.py if request.user.is_authenticated(): queryset = Controls.objects.filter(requirement_version=requirement).filter(relatedfiles__team=request.user.team_id) else: queryset = Controls.objects.filter(requirement_version=requirement) -
Django; TemplateDoesNotExist error - blog app
Im trying to create a blog application following an oline tutorial but an struggling with loading some templates. It seems as if the templates in blog/templates/blog/... cannot be found. The page http://127.0.0.1:8000/blog/ loads fine. Included below is the current code from the settings.py, views.py and urls.py file. settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # third party installs go here. 'products', 'pages', 'blog', ] ... TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates")], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] views.py from django.shortcuts import render, get_object_or_404 from django.http import Http404 # Create your views here. from .models import BlogPost def blog_post_list_view(request): qs = BlogPost.objects.all() # queryset -> list of python objects template_name = 'blog/blog_post_list.html' context = {"object_list": qs} return render(request, template_name, context) def blog_post_create_view(request): # create objects #template_name = 'blog/blog_post_create.html' context = {"form": None} return render(request, "blog/blog_post_create.html", context) def blog_post_detail_view(request, slug): obj = get_object_or_404(BlogPost, slug=slug) template_name = 'blog_post_detail.html' context = {"object": obj} return render(request, template_name, context) def blog_post_update_view(request, slug): obj = get_object_or_404(BlogPost, slug=slug) template_name = 'blog_post_update.html' context = {"object": obj, 'form': None} return render(request, template_name, context) def blog_post_delete_view(request, slug): obj = get_object_or_404(BlogPost, slug=slug) template_name = … -
Django: When a user uploads media to my site, it is owned by the server's root user. How do I change this?
I am unsure of what code you guys would want me to upload, but please ask away if you need any and I will upload it! When a user uploads media/files to my website, the root user becomes the owner of the file. This prevents the user from being able to open and view the media they uploaded, because it is not owned by the proper user on my server. I have a user that runs my Django application instead of the root user. The person who uploaded the media can access it once I manually go into the server and change the ownership to that media file that was uploaded, to the server user which runs my Django application. How can I get this to, by default, upload the file to the ownership of the server user running Django?? I was thinking of setting up a cron job to run every-so-often (this would be terrible for scaling) so I can change the ownership of the media without having to physically going in the server and do it myself. -
How safely reuse database records in MySql from Django (in Apache)
Long story short: In Django web application on Apache2 (linux) and MySql (ISAM) we need safely reuse some records marked as deleted, instead of creating new ones. Even if more users may request such action at the same time, each of them should obtain different record for reusing. The background: We have web application, where many users can do things at the same time. there are tables, that grows to infinity, but only few records are active (sometimes like from 100.000 long records is active 1.000 and no chance for reactivating any "deleted") sometimes are tranferred (to other places) just changes, so we mark "deleted" records as such and transfer them to delete records on the other side sometimes is needed to transfer the tables (to partial place) as whole and it takes too long the data integrity during the transfer is managed by other part of the project and should not do real problems Wanted: reuse some old and long time "deleted" records for new data it is not problem, to have reuse_me field in tables (default False, set to True after long time deleted, by some script). It can be safely assumed, that such records are nowhere referenced … -
DRF error: Could not resolve URL for hyperlinked relationship using view name on nested serializer
I am getting the following error on DRF: django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "quotationitemfile-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. I did a Google search on this and it seems an error related to the HyperlinkedModelSerializer, but the thing is that I am not using it, I am using regular serializers: class QuotationItemFileSerializer(serializers.ModelSerializer): class Meta: model = QuotationItemFile class QuotationItemSerializer(serializers.ModelSerializer): files = QuotationItemFileSerializer(many=True) class Meta: model = QuotationItem class QuotationSerializer(serializers.ModelSerializer): items = QuotationItemSerializer(many=True) class Meta: model = Quotation And this error happens when a send a request to a ViewSet using the QuotationSerializer. I also noticed that the error disappears if I comment out the QuotationItemFileSerializer so I guess this is something related to DRF falling back to hyperlinks automatically. But I can't seem to get this to work propertly -
Django running a JS script that requires a JSON returning Not Found (static collected)
Disclaimer: I know very little Javascript I'm trying to run a TensorflowJS in a Django instance, I can successfully load the JS to call the tf.loadLayersModel function, however this function requires a json file (and another .bin file later) to run and the function isnt able to find it. Both the files (json and bin) are in the expected static directory (the same that loaded the JS file in the first place), but everytime I load the page Django returns Not Found: /myapp/test_model/model.json and the browser returns (through Inspect Element) Error: Request to model.json failed with status code 404. Please verify this URL points to the model JSON of the model to load. I'm using in settings.py: STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) Directory: myproject/ ++ static/ #(created by django) ++ __init__.py ++ settings.py ++ ... myapp/ static/ #(where I'm putting the files) ++ myapp/ ++++ test_model/ ++++++ model.json ++++++ otherfile.bin manage.py So the files are put in the static/myapp/test_model/ and after that i run python manage.py collectstatic the files get reconized, and copy to myproject/static/myapp/test_model/ The .html loaded at the view: (localhost/myapp/test_model/) <html> <head> {% load static %} ... <script src = "{% static "myapp/test_model/main.js" %}" > </script> </head> … -
ModelForm has no model class specified for dyanmic django forms
Getting an error here showing that my form field ModelForm has no model class specified. class CartForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # get all the items in the cart model items = forms.ModelMultipleChoiceField(widget=forms.ChoiceField, queryset=Cart.objects.all()) for i in range(len(items) + 1): field_name = 'items_%s' % (i,) self.fields[field_name] = forms.ChoiceField(required=False) try: self.initial[field_name] = items[i] except IndexError: self.initial[field_name] = '' # create a blank choice field field_name = 'items_%s' % (i + 1,) self.fields[field_name] = forms.ChoiceField(required=False) def get_item_fields(self): for field_name in self.fields: if field_name.startswith('items_'): yield self[field_name] The cart model in the queryset has foreign keys and those keys have already been populated with model instances. -
How can I decrease the value of a field of a queryset simultaneously?
I want to make a site where people can make listings for things to sell. I want it to have a front page where the most popular (hot) items are always displayed. Popularity decreases with time and increases with activity (bidding, commenting, clicking). Every item starts with a popularity of 100. That way uninteresting items dissapear quickly and interesting ones stay on longer. So everytime a user interacts with the objects its popularity should increase (for example, everytime a get request from a unique user is made for the details of the object, its popularity value goes up by 1, every bid increases it by 10). On the opposite, everytime a minute or so passes, the popularity of all currently active items decreases. Once it hits 0, it will be "deactivated" it will still be tradable, but it will never hit the frontpage again. The problem is, how do I decrease the popularity of a queryset of all active items? I realize that everytime the user request the front page. I could just fetch all active objects, calculate the popularity within python code and sort them by hand, but that seams rather wastefull. I know I can easily set a … -
How do you clone a model and its dependencies in Django 2.2?
How do I clone a model in such a way that it includes (clones) data on FK-related models? I've looked through various related questions on Stack, and found most of them are for old/outdated versions of Django. Here's some illustrative model code (with str methods, etc omitted for brevity): class Tracking(models.Model): entry = models.CharField(blank=False, max_length=50) timestamp = models.DateTimeField(null=True, auto_now_add=True) active = models.BooleanField(default=False) class Author(models.Model): entry = models.ForeignKey(Tracking, on_delete=models.CASCADE) first_name = models.CharField(blank=False, max_length=50) last_name = models.ImageField(null=True, blank=True) class Scene(models.Model): entry = models.ForeignKey(Tracking, on_delete=models.CASCADE) location = models.CharField(blank=False, max_length=50) image = models.ImageField(null=True, blank=True) My desired result would be to clone an existing "entry" on the Tracking model, such that a new "entry" on a new row is created with its own PK, as well as cloned copies of "Author" and "Scene" data on their respective tables which also point to the new cloned "entry". Any pointers in the right direction would be helpful. I'm not finding anything in the django docs. -
'Keyerror at /' when passing user with primary key in queryset for a listview
models.py class Notes(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) content = models.TextField() date_added = models.DateTimeField(default=timezone.now) views.py class HomepageView(ListView): model = Notes template_name = "home.html" def get_queryset(self): # object_list = Notes.objects.filter(Q(author=self.kwargs['pk'])) return Notes.objects.filter(Q(author=self.kwargs['pk'])) It points out pk has KeyError, is there any way to get rid of it Thanks in advance...! -
SSH tunnel (via Serveo.net) not connecting to Django server
I'm using Django to host a small server (i.e. etesync), and while I'm not fully familiar with all the technical details that go into this sort of thing, I know that I run the server at 0.0.0.0:8000. I can confirm that it connects successfully when I navigate to http://localhost:8000/ and http://192.168.1.XXX:8000/ (where XXX is local device's static IP). I'm trying to set up an SSH tunnel to Serveo.net so I can access this server from outside my LAN. So, I ran: ssh -R xyz:80:localhost:8000 serveo.net in my SSH client and received the output, "Forwarding HTTP traffic from https://xyz.serveo.net." If I then navigate to http://xyz.serveo.net/, my SSH client will output, "HTTP request from [my external IP] to https://xyz.serveo.net/." However, it does not connect to my Django server. In the python terminal where I'm running my server, I do not see any new requests (whereas navigating to http://localhost:8000/ will output, "GET HTTP/1.1" for the server). Am I doing something wrong with configuring Serveo? As this is my first project involving hosting and SSH, I'm not super familiar with what the "80" in "80:localhost:8000" refers to. I've tried changing this to: ssh -R xyz:8000:localhost:8000 serveo.net but that just results in the output, "Warning: … -
Annotate and Extract to Group Attribute returns 'Sequence Item 0'
I'm trying to build a query to count occurrences from distinct months in my SQL DB, using annotate and extract for this purpose. Here is the code used: Model class Results(model.Model): trip = models.BooleanField(default=False) created_on = models.DateTimeField(default=datetime.now) Query from django.db.models.functions import Extract, ExtractYear from django.db.models import Count res = Results.objects.annotate(month=ExtractMonth('created_on')) .values('month').annotate(count=Count('month')) OR res = Results.objects.annotate(month=Extract('created_on','month')) .values('month').annotate(count=Count('month')) Both return: Error Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\VIBRITO\Desktop\Projetos\webapp\venv\lib\site-packages\django\db\models\query.py", line 244, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "C:\Users\VIBRITO\Desktop\Projetos\webapp\venv\lib\site-packages\django\db\models\query.py", line 268, in __iter__ self._fetch_all() File "C:\Users\VIBRITO\Desktop\Projetos\webapp\venv\lib\site-packages\django\db\models\query.py", line 1186, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\VIBRITO\Desktop\Projetos\webapp\venv\lib\site-packages\django\db\models\query.py", line 106, in __iter__ for row in compiler.results_iter(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size): File "C:\Users\VIBRITO\Desktop\Projetos\webapp\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1017, in results_iter results = self.execute_sql(MULTI, chunked_fetch=chunked_fetch, chunk_size=chunk_size) File "C:\Users\VIBRITO\Desktop\Projetos\webapp\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1052, in execute_sql sql, params = self.as_sql() File "C:\Users\VIBRITO\Desktop\Projetos\webapp\venv\lib\site-packages\django\db\models\sql\compiler.py", line 449, in as_sql extra_select, order_by, group_by = self.pre_sql_setup() File "C:\Users\VIBRITO\Desktop\Projetos\webapp\venv\lib\site-packages\django\db\models\sql\compiler.py", line 50, in pre_sql_setup self.setup_query() File "C:\Users\VIBRITO\Desktop\Projetos\webapp\venv\lib\site-packages\django\db\models\sql\compiler.py", line 41, in setup_query self.select, self.klass_info, self.annotation_col_map = self.get_select() File "C:\Users\VIBRITO\Desktop\Projetos\webapp\venv\lib\site-packages\django\db\models\sql\compiler.py", line 244, in get_select sql, params = self.compile(col, select_format=True) File "C:\Users\VIBRITO\Desktop\Projetos\webapp\venv\lib\site-packages\django\db\models\sql\compiler.py", line 390, in compile sql, params = node.as_sql(self, self.connection) File "C:\Users\VIBRITO\Desktop\Projetos\webapp\venv\lib\site-packages\django\db\models\aggregates.py", line 76, in as_sql return super().as_sql(compiler, connection, **extra_context) File "C:\Users\VIBRITO\Desktop\Projetos\webapp\venv\lib\site-packages\django\db\models\expressions.py", line 618, in as_sql data['expressions'] = data['field'] = … -
How to calculate count of related many to many objects based on another queryset?
class Zone(Model): ... class Flight(Model): zones = ManyToManyField(Zone) flights = Flight.objects.filter(...) qs1 = Zone.objects.annotate( count=flights.filter(zones__pk=F('pk')).distinct().count(), # this is not valid expression ) Despite having F inside queryset with count() in annotation it still throw an error TypeError: QuerySet.annotate() received non-expression(s): 0. meaning that that queryset was executed in place. Also doesn't work: qs1 = Zone.objects.annotate( count=Count('pk', filter=flights.filter(zones__pk=F('pk'))), ) -
Django: How to validate / Validator a "greater then" between two FormFields?
I am testing writing validator in django. So far it worked, but now i would like to write something like a "range". forms.py class AnimalForm(forms.ModelForm): weight = forms.DecimalField(validators=[validate_gtr]) class Meta: model = Animal fields = [ 'name', 'weight', 'daily_food_min', 'daily_food_max', 'species', 'farmer', ] def __init__(self, *args, **kwargs): super(AnimalForm, self).__init__(*args, **kwargs) self.fields['name'].help_text = 'Name of Animal' self.fields['weight'].help_text = 'Weight in Kg' self.fields['species'].help_text = 'choose a species' validator.py from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ def validate_gtr(value): if value > 100: raise ValidationError( _('(value) Kg. Animal is too heavy'), params={'value': value}, ) Question As you can see i already wrote a simple validation validate_gtr to check the weight of my animals - it worked. Now i would like to validate daily_food_min and daily_food_max against each other, meaning that daily_food_max has to be greater then daily_food_min, when saving or when entering the numbers in my html form. this was my approach forms.py class AnimalForm(forms.ModelForm): weight = forms.DecimalField(validators=[validate_gtr]) daily_food_min = forms.IntegerField(min_value=0, validators=[validate_food]) daily_food_max = forms.IntegerField(min_value=1, validators=[validate_food]) <...> validator.py <...> def validate_food(daily_food_min, daily_food_max): if daily_food_min > daily_food_max: raise ValidationError( _('(daily_food_min) Kg. is higher then max.'), params={ 'daily_food_max': daily_food_max, 'daily_food_min': daily_food_min, }, ) Unfortunately i receive i Error Message when i fill out … -
assign foreign key to user custom field
i am trying t assign the foreign key of a model to specific custom field in custom user model. how should i handle it in the views. def create_generalinfoform(request): args = {'startup_id':request.user} if request.method == 'POST': form = generalinfoform(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.str_geninfo_id = args.startup_name instance.save() return redirect('create_teamsizeform') else: form = generalinfoform() return render(request, 'application/form_template.html', {'form': form}) -
how to retrieve data related to a primary key when selected from a form before saving the instance
how to retrieve data related to a primary key when selected from a form before saving the instance i'm trying to something like that , when i selected a model for instance dell venue before i hit the save button it will return the related data depend on the primary key without saving the instance <form method="POST" id="print-form">{% csrf_token %} <div class="card text-center box-2" id="print-form"> <table class="table"> <thead> <tr> <th class="float-right"> Date : {{ form.date }}</th> <th class="float-left">Customer : {{ form.customer }}</th> </tr> </thead> </table> <table class="table"> <thead> <tr> <td scope="col">model</td> <td><div class="form-group floating-label"> {{ form.model | add_class:'form-control select2-list' | attr:'id:model'}} </div></td> </tr> <tr> {{ form.order.errors }} <td scope="col">quantity</td> <td scope="col">{{form.order}}</td> </tr> <tr> {{ form.CPU.errors }} <td scope="col">CPU</td> <td scope="col" style="width: 50%">{{form.CPU}}</td> </tr> <tr> {{ form.RAM.errors }} <td scope="col">RAM</td> <td scope="col">{{form.RAM}}</td> </tr> <tr> {{ form.Hard.errors }} <td scope="col">Hard</td> <td scope="col">{{form.Hard}}</td> </tr> <tr> {{ form.Graphic.errors }} <td scope="col">Graphic</td> <td scope="col">{{form.Graphic}}</td> </tr> <tr> {{ form.price.errors }} <td scope="col">price</td> <td scope="col">{{form.price}}</td> </tr> <tr> {{ form.get_cost.errors }} <td scope="col">cash</td> <td scope="col">{{form.get_cost}}</td> </tr> <tr> {{ form.guarantee.errors }} <th>warrantor</th> <th>{{form.guarantee}}</th> </tr> </tbody> </table> <input type="submit" name="save" value="selling" class="btn btn-primary btn-block"> ... is it possible to retrieve the data before saving the form?