Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Elastic search with django
Am working with elastic search with Django where I find difficult to map parent child relationship.here is my code.Here category is a child of division and they have many to one relationship. @registry.register_document class DivisionDoc(Document): id = fields.IntegerField(attr="id") code = fields.TextField( fields={ "raw":{ "type":"keyword" } } ) name = fields.TextField() is_active = fields.BooleanField() is_delete = fields.BooleanField() status = fields.TextField() division_meta = fields.NestedField() class Index: name = 'division' settings = { 'number_of_shards':1, 'number_of_replicas':1 } class Django: model = Division @registry.register_document class CatgeoryDoc(Document): id = fields.IntegerField() parent = fields.NestedField() division_id = fields.ObjectField(properties={ 'id': fields.IntegerField(), 'code': fields.TextField(), 'name': fields.TextField(), 'is_active': fields.BooleanField(), 'is_delete': fields.BooleanField(), 'status' :fields.TextField(), 'division_meta' : fields.NestedField() }) code = fields.TextField( fields = { "raw":{ "type":"keyword" } } ) name = fields.TextField() image = fields.FileField() is_active = fields.BooleanField() is_delete = fields.BooleanField() status = fields.TextField() category_meta = fields.NestedField() class Index: name = 'category' settings = { 'number_of_shards':1, 'number_of_replicas':1 } class Django: model = Category class DivisionDocuments(DocumentViewSet): permission_classes = [AllowAny] document = DivisionDoc def get_serializer_class(self): if self.action == 'list': return DivisionSerializer filter_backends = [ FilteringFilterBackend, CompoundSearchFilterBackend ] search_fields = ('code','name') multi_match_search_fields = ('code','name') filter_fields = { 'code':'code', 'name':'name' } class CategoryDocuments(BaseDocumentViewSet): permission_classes = [AllowAny] document = CatgeoryDoc lookup_field = 'id' # serializer_class = CategorySerializer … -
should I run daphne + gunicorn or just dapne? why?
I have created a real-time RESTful application that uses Django channels and was referring to this link to host my application. It works. But I was wondering do we need daphne+gunicorn when the app runs with daphne alone. Is there any benefit/drawback of just running daphne apart from the easier configuration? -
React/Django - ImageField (when no uploding any file) - The submitted data was not a file. Check the encoding type on the form
I want not to upload any image when submitting but it is giving me an error The submitted data was not a file. Check the encoding type on the form. When I select a file it works fine. How can fix this, I also try some methods. I try removing image when it get null and set default in models views.py class ProductViewset(ModelViewSet): serializer_class = ProductSerializer queryset = Product.objects.all() def create(self, request, *args, **kwargs): data = format_product_data(request.data.copy()) serializer = self.get_serializer(data=data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) pprint(serializer.validated_data) headers = self.get_success_headers(serializer.data) return Response(format_product_response_data(serializer.data), status=201, headers=headers) serializer.py class ProductSerializer(ModelSerializer): image = serializers.ImageField(max_length=None, use_url=True, allow_empty_file=True) attrs = ProductAttrSerializer(many=True, required=False, read_only=False) type = serializers.PrimaryKeyRelatedField(read_only=False, required=True, allow_null=False, allow_empty=False, queryset=ProductType.objects.all()) class Meta: fields = "__all__" model = Product def create(self, validated_data): attr_list: List[dict] = [] if 'attrs' in validated_data: attrs = validated_data['attrs'] del validated_data['attrs'] for attr in attrs: attr_serializer = ProductAttrSerializer(data=attr) attr_serializer.is_valid(raise_exception=True) attr_list.append(attr_serializer.save()) instance = Product.objects.create(**validated_data) instance.attrs.set(attr_list) instance.save() return instance models.py class Product(models.Model): number = models.CharField(max_length=20, null=True, unique=True, blank=True, db_column='NO.') name = models.CharField(max_length=30, null=True, unique=False, db_column='Name') image = models.ImageField(upload_to="product_images", blank=True, null=True, db_column='Image') entry_date = models.DateTimeField(auto_now_add=True, db_column='Date', null=True, blank=True) last_updated = models.DateTimeField(auto_now=True, db_column='Update_date') source_type = models.CharField(max_length=10, blank=False, choices=PRODUCT_TYPES, default="spd") type = models.ForeignKey(to=ProductType, on_delete=models.CASCADE, related_name="products", related_query_name="product") status = models.CharField(max_length=8, null=False, blank=False, choices=PRODUCT_STATUS_CHOICES, … -
What changes I should make change the get to filter?
I am doing a project for my college work. In that, I need to change a function. That function is giving error saying multiple objects returned. The function works well if there is only one object to return. But I need to change it to return it to return all the objects. So what changes do I need to do. I am attaching the function code. Pls provide the code to modify also. I am just beginner in coding. Thanks I am using Pycharm, Django and. MySQL to do my project The problem is obj=booking.objects.get is returning multiple objects and it can't displayed by the function . So I need to get the code to display all objects. I understood that using filter() will solve the problem. But I don't know what are the changes to make and where should I make it. So pls help. I am just a beginner. def vpay(request) : b=request.session['uid'] ob=TurfManager.objects.get(t_id=b) bb=ob.tf_id obj=Booking.objects.get(tf_id=bb) nn=obj.b_id o = Payment.objects.filter(book_id=nn) context = { 'obval': o, } -
How to instantiate Annotorious.js API with Django
I am trying to include Annotorious.js in a Django Web app. Using the steps from annotorious documentation, I am able to annotate an image at the front end. But, I could not save the coordinates of the drawn annotation. Is there a way to instantiate the annotorious APIs with Django, such that any changes to the bounding boxes drawn at the front end be saved automatically? -
How to effectively query DB when need to build paginated view for big table and join extra details from small one?
I'm trying to understand typical approaches for the below common situation faced when developing on Rails or Django. Example user story I want to filter and sort purchases and then expand details about some purchased products by clicking on their lines and to see details right there. Go to the next pages if needed. Data model details Big table with purchases (millions). Small table with products details (thousands). Only one product per purchase. Main question How to organize the processing of such request to gain the best performance? Does framework ORM have any effect on it? There are likely many 'it depends'. I will appreciate it if you point them out. Smaller questions Even when we provide all data in one HTTP request: is there a case to split queries into two? First WHERE's, ORDER, OFFSET and LIMIT for big table. Then go with the result to a small table to join. If done in one query: is it a common approach to subset with WITH first and only then do join? Is it correct understanding that generally ORM query builder will do one big query, so if one wants to optimize SQL requests, then one needs to bypass ORM? … -
How to display parsed JSON data into different tables based on matching list criteria
Have a feeling there is an easy solution for this, but I am spinning my wheels here. I am building a simple Django website that will have 10 different tables, each table will have unique sports teams listed with associated stats like scores, wins, losses, etc. I am parsing JSON data from an API that has all this information. The issue I am running into is how to specifically designate say Team1, Team2, Team3, Team4 goes to first table, and Team5, Team6, Team7, Team8 to the second table, etc. I have tried multiple different ways with no good results. For simplicity lets just say we are working with just two tables, here is snippet from my views.py file def bball(request): url = "https://api-URL" querystring = {"criteria":"criteria","criteria":"criteria"} headers = { 'x-rapidapi-host': "api-host", 'x-rapidapi-key': "APIKEY" } jsonList = [] response = requests.request("GET", url, headers=headers, params=querystring) data = json.loads(response.content) main = data["get"] league = data["parameters"]["league"] season = data["parameters"]["season"] temp_main = data["response"] final = list() table_1 = ["TEAM1","TEAM2","TEAM3","TEAM4"] table_2 = ["TEAM5","TEAM6","TEAM7","TEAM8"] for temp in temp_main: for record in temp: position = record['position'] stage = record['stage'] group_name = record["group"]["name"] group_points = record["group"]["points"] team_id = record["team"]["id"] team_name = record["team"]["name"] games_played = record["games"]["played"] games_won_total = record["games"]["win"]["total"] games_won_perct … -
What's the recommended way for me to decouple csv parsing and data saving in Django?
Novice here. I'm using Django Rest Framework to create an API that a user can post a csv file to. My program then parses the csv and creates model instances to save data in my database. I've heard that it's best practice to decouple processes like csv parsing and saving data to the database. I haven't found any helpful examples of what this might look like on google, though. In my view I'm currently using csv.DictReader(csv_contents.splitlines()) to begin deserializing the contents of the csv, and then I'm calling a method from my services.py file to go through the csv contents and create my model instances. Can anyone recommend a better way for me to design this process? Thank you so much for your time. -
Django group nearby rows based on datetime
In a Django model that stores an event datetime, I would like to group rows nearby in datetime. To clarify, each object has a date_time field and I can find the gap between objects in date time rather easily with: # We want a minimum date_time as the default for prev_date_time # but because Session.date_time is a DateFimeField and TZ aware # Django requires teh default to be TZ aware. And datetime.min # cannot be made TZ awre (it crashes), adding one day prevents # that crash and works and serves our purposes. min_date_time = make_aware(datetime.min + timedelta(days=1), "UTC") sessions = Session.objects.all().annotate( prev_date_time=Window( expression=Lead('date_time', default=min_date_time), order_by=F('date_time').desc() ), dt_difference=F('date_time') - F('prev_date_time') ) This works brilliantly. Now, I would like to group these sessions such that any session with a dt_difference of over 1 day marks a group boundary. I imagine two new annotations could do the trick, but I am struggling to write them and would ideally like to do so without resorting to raw SQL. A new annotation that is equal to the date_time of the session when dt_difference is greater than one day, null otherwise. A new annotation that fills all these nulls with the first non-null value (in … -
Ordering not rendering the way I prefer when compared to sqlite and postgres
I am using django templatetag regroup to nest grouping in template, my problem is that regroup is not working the way I want for some reason it works well in sqlite but not in postgres #My Model class Question(models.Model): TEXT = "textarea" TEXT_MULTIPLE = "textmultiple" SHORT_TEXT = "text" RADIO = "radio" CHECKBOX = "checkbox" DATE = "date" NUMBER = "number" SELECT = "select" FIELD_TYPE = ( (TEXT, "Long text"), (SHORT_TEXT, "Short text"), (TEXT_MULTIPLE, "Text multiple"), (RADIO, "Radio"), (CHECKBOX, "Checkbox"), (DATE, "Date"), (NUMBER, "Number"), (SELECT, "Select"), ) field_type = models.CharField(choices=FIELD_TYPE, default=SHORT_TEXT, max_length=13) category = models.ForeignKey( Category, on_delete=models.CASCADE ) section = models.ForeignKey( Section, on_delete=models.CASCADE, blank=True, null=True, help_text="Sub category", ) prompt = models.TextField(help_text="Question name") required = models.BooleanField(default=True, help_text="Required") help_text = models.TextField(blank=True, help_text="Description for question") disabled = models.BooleanField(default=False, help_text="Disable field") enable_status = models.BooleanField( default=True, help_text="Enable status for questionaire" ) enable_date = models.BooleanField(default=True, help_text="Enable date") enable_field = models.BooleanField(default=True, help_text="Enable Input field") question_number = models.CharField( blank=True, max_length=255, help_text="Question number" ) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) created_by = models.ForeignKey( User, blank=True, null=True, on_delete=models.CASCADE, help_text="Created by" ) def __str__(self): return self.prompt #My view def question_list(request, company_id=None): categories = Category.objects.all() company_id = request.session.get("company_id") category = Category.objects.first() questions = "" if category is not None: try: questions = category.question_set.all().order_by("category") … -
Django REST framework - sumbit only fields?
I use a model serializer in my code and need to get extra field value in the PUT request. This is to identify the user intention on certain operations. I see there is read_only and write_only option in serialize fields. But I can't use those since I'm not going to store this additional field to the model (it don't have such field). How can I achieve this in the serializer correct way? djangorestframework version 3.13.1 -
django method logic related to a model with DRF
Im learning Django/DRF and i have a grasp on most concepts but I don't know the answer for this and i can't find the answer on the internet. Here is a model (ignore the id being a charfield please that doesnt auto increment) class Competition(models.Model): id = models.CharField(primary_key=True, max_length=7) buyer = models.ForeignKey(Buyer, on_delete=models.CASCADE,related_name='competition_buyer_id') name = models.CharField(max_length=200) open = models.DateTimeField() closed = models.DateTimeField() minimum_capacity = models.IntegerField() currency = models.CharField(max_length=5) I have logic related to this model which I put into a utils folder inside this app from django.utils import timezone class CompetitionHandler: def get_state_based_on_open_and_closed_dates(self, open_date_object, closed_date_object): state = None if open_date_object > timezone.now() and closed_date_object > timezone.now(): state = 'pending' if open_date_object < timezone.now() and closed_date_object > timezone.now(): state = 'open' if open_date_object < timezone.now() and closed_date_object < timezone.now(): state = 'closed' return state def main(): CompetitionHandler() if __name__ == '__main__': main() then I called it in the serializer for this model like so: from buyer.serializers import BuyerSerializer from competition.models import Competition from rest_framework import serializers from business_logic.competition import CompetitionHandler class CompetitionSerializer(serializers.ModelSerializer): status = serializers.SerializerMethodField() buyer = BuyerSerializer('buyer') class Meta: model = Competition fields = '__all__' def get_status(self, competition): competition_handler = CompetitionHandler() state = competition_handler.get_state_based_on_open_and_closed_dates( competition.open, competition.closed) is this bad practice? … -
If statement is not working for me in Django “views.python file “
[enter image description here][1] The codes there are not working and i don’t know why.When I click signup, I want the user information to be saved if all the inputs are valid and redirects to the page specified but when I click on sign up, nothing happens [1]: https://i.stack.imgur.com/tLUt4.jpg -
List is being split into characters when passed through url
I have a city_list I pass from the first view to the second view through the url. When I pass that list to the second view and iterate through it, it iterates through every character rather than the strings in the list. I'm not sure why this is and was wondering how to have the full list passed with the strings it contains. first view template <button id="price_button1" hx-post="{% url 'get_price' price_object.id user_city city_list 1 %}">Click</button> first view city_list = ["Montreal", "Milan", "Paris", "Singapore", "Barcelona", "Rome"] second view def get_price(request, id, user_city, city_list, number): for city in city_list: print(city) output is [ " M O N T R E A L instead of Montreal -
How to loop jQuery / JavaScript in Django template
I have the following in a Django template (*.html): <script> $.get('{% url 'json0' %}', function (data) { blah blah blah; $("#mychart0").highcharts(data); }); $.get('{% url 'json1' %}', function (data) { blah blah blah; $("#mychart1").highcharts(data); }); ... ... </script> each $get(){} is similar, except that the url name is json0,json1,json2,.... and the element id is mychart0, mychart1, mychart2, ... So instead of having multiple $gets, how do I increase the enumeration with a single loop? Moreover, in my template I have: {% for num in Charts %} <div id="myChart{{forloop.counter}}"></div> {% endfor %} The latter works ok but I don't know how to do something similar in the script tag. In particular I wish I could use the same counter, i.e., 'for num in charts'. Thanks a lot for your help. I just cannot find a solution -
Is there any other way to structure this HTML table for better performance?
I am currently wrestling with a performance issue with my Formset table. I've worked to rule out issues with the server side...but am wondering if perhaps there is a better way to structure my HTML for performance purposes? Here is my HTML code with the relevant Django Formset template. Thanks in advance for any thoughts... <div class="table4"> {{ budget_line_item_form.management_form }} {{ budget_line_item_form.non_form_errors }} {% for form in budget_line_item_form %} {{ form.id }} <div class="inline {{ budget_line_item_form.prefix }}"> <table class="table3"> <thead> <tr> <th>Description</th> <th>Vendor</th> <th>Product</th> <th>Service</th> <th>Cost Center</th> <th>January</th> <th>February</th> <th>March</th> <th>April</th> <th>May</th> <th>June</th> <th>July</th> <th>August</th> <th>September</th> <th>October</th> <th>November</th> <th>December</th> <th>Total</th> </tr> </thead> <tbody> <tr> <th>{{ form.line_item_description }}</th> <td>{{ form.line_item_vendor }}</td> <td>{{ form.line_item_product }}</td> <td>{{ form.line_item_service }}</td> <td>{{ form.line_item_cost_center }}</td> <td>{{ form.budget_line_item_january }}</td> <td>{{ form.budget_line_item_february }}</td> <td>{{ form.budget_line_item_march }}</td> <td>{{ form.budget_line_item_april }}</td> <td>{{ form.budget_line_item_may }}</td> <td>{{ form.budget_line_item_june }}</td> <td>{{ form.budget_line_item_july }}</td> <td>{{ form.budget_line_item_august }}</td> <td>{{ form.budget_line_item_september }}</td> <td>{{ form.budget_line_item_october }}</td> <td>{{ form.budget_line_item_november }}</td> <td>{{ form.budget_line_item_december }}</td> <td>{{ form.budget_line_item_total }}</td> {{ form.budget_pk.as_hidden }} {{ form.budget_line_item_april_confirm.as_hidden }} {{ form.budget_line_item_august_confirm.as_hidden }} {{ form.budget_line_item_december_confirm.as_hidden }} {{ form.budget_line_item_february_confirm.as_hidden }} {{ form.budget_line_item_january_confirm.as_hidden }} {{ form.budget_line_item_july_confirm.as_hidden }} {{ form.budget_line_item_june_confirm.as_hidden }} {{ form.budget_line_item_march_confirm.as_hidden }} {{ form.budget_line_item_may_confirm.as_hidden }} {{ form.budget_line_item_november_confirm.as_hidden }} {{ form.budget_line_item_october_confirm.as_hidden }} {{ form.budget_line_item_september_confirm.as_hidden }} {{ form.budget_line_item_total_confirm.as_hidden }} … -
Issue extending django.contrib.auth User model. Django + legacy MySQL
I'm unclear which Django-generated default-model I should keep after extending the AuthUser model with a custom "NewUser" model I'll first explain the status and at the bottom, I'll ask the question. My installed apps are: 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', After syncing the MySQL database to the Django project, Django added the default user, permission, sessions, etc. tables to the database. Then I ran "inspectdb > models.py" to get the models pasted into my model.py. Here only show the Django generated ones: class AuthGroup(models.Model): name = models.CharField(unique=True, max_length=150) class Meta: managed = True db_table = 'auth_group' class AuthGroupPermissions(models.Model): id = models.BigAutoField(primary_key=True) group = models.ForeignKey('AuthGroup', models.DO_NOTHING) permission = models.ForeignKey('AuthPermission', models.DO_NOTHING) class Meta: managed = True db_table = 'auth_group_permissions' unique_together = (('group', 'permission'),) class AuthPermission(models.Model): name = models.CharField(max_length=255) content_type = models.ForeignKey('DjangoContentType', models.DO_NOTHING) codename = models.CharField(max_length=100) class Meta: managed = True db_table = 'auth_permission' unique_together = (('content_type', 'codename'),) class AuthUser(models.Model): password = models.CharField(max_length=128) last_login = models.DateTimeField(blank=True, null=True) is_superuser = models.IntegerField() username = models.CharField(unique=True, max_length=150) first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) email = models.CharField(max_length=254) is_staff = models.IntegerField() is_active = models.IntegerField() date_joined = models.DateTimeField() class Meta: managed = True db_table = 'auth_user' class AuthUserGroups(models.Model): id = models.BigAutoField(primary_key=True) user = models.ForeignKey('AuthUser', models.DO_NOTHING) group = … -
Got an error creating the test database: could not read file "base/1/1249": I/O error
When i try sudo docker-compose run python python manage.py test I've got this Eror: Starting bstr_sa_backend_sa_db_1 ... done Creating test database for alias 'default'... Got an error creating the test database: could not read file "base/1/1249": I/O error -
Django 4 with drf_spectacular Swagger does not execute POST
I have the following classes using the django-restframework and drf-spectacular. I can execute POST when I am logged in and through the drf default routes, but not using the swagger-ui routes. I can go to this url: http:/example.com/api/schema/swagger-ui/#/organism/organism_create But when I click the Execute button, nothing really happens. I expect the CURL command to be shown etc. Also, I don't see a response at the server backend. Contrary to the GET method. Here, the server prints: 11/Feb/2022 22:34:02] "GET /api/organism/ HTTP/1.1" 200 275 I did go to login, and provided my username and password first. What is wrong with this setup? models.py class Organism(models.Model): short_label = models.CharField(max_length=100) long_label = models.CharField(max_length=100) genus = models.CharField(max_length=100) def __str__(self): return self.long_label serializers.py class OrganismSerializer(serializers.ModelSerializer): class Meta: model = models.Organism fields = ('__all__') views.py class ReadOnly(BasePermission): def has_permission(self, request, view): return request.method in SAFE_METHODS class OrganismViewset(viewsets.ModelViewSet): queryset = models.Organism.objects.all() serializer_class = serializers.OrganismSerializer parser_classes = [parsers.MultiPartParser, parsers.FormParser] http_method_names = ['get', 'post', 'patch', 'delete'] # Permissions permission_classes = [IsAuthenticated|ReadOnly] def get(self, request, format=None): content = { 'status': 'request was permitted' } return Response(content) urls.py router = SimpleRouter() router.register('organism', views.OrganismViewset) settings.py I tried different settings. Using the BasicAuth.., I get a prompt asking for username and password, but … -
"ValueError: source code string cannot contain null bytes" when trying to run a Django server
I cloned a project from github that works on another computer. When I run the server with the command "python3 manage.py runserver" I get the following error: File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 846, in exec_module File "<frozen importlib._bootstrap_external>", line 983, in get_code File "<frozen importlib._bootstrap_external>", line 913, in source_to_code File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed ValueError: source code string cannot contain null bytes I tried to delete bootstrap4 but the problem persists... Thanks in advance. -
Django API IntegrityError insert or update on table
This is my error , i am using postgresql , what is problem ? insert or update on table "Auth_user_org_user_id" violates foreign key constraint "Auth_user_org_user_id_user_id_17f17996_fk_auth_user_id" DETAIL: Key (user_id)=(1) is not present in table "auth_user". This is models class User(models.Model): FirstName = models.CharField(blank=True,null=True,max_length=100) LastName = models.CharField(blank=True,null=True,max_length=100) mail = models.CharField(blank=True,null=True,max_length=100) def __str__(self): return str(self.FirstName) class Organization(models.Model): id = models.AutoField(primary_key=True,blank=True) name = models.CharField(max_length=100) type = models.CharField(max_length=20) def __str__(self): return str(self.id) class User_org(models.Model): id = models.AutoField(primary_key=True,blank=True) user_id = models.ManyToManyField(User,related_name='UserInfo') organization_id = models.ForeignKey(Organization,related_name='orginfo',on_delete=models.CASCADE) and this is views.py class UserSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserForSerializer class OrgSet(viewsets.ModelViewSet): queryset = Organization.objects.all() serializer_class = OrganizationSerializer #test class User_and_Org_Set(viewsets.ModelViewSet): queryset = User_org.objects.all() serializer_class = User_and_org_Serializer what is problem and how to slove this ? i can insert models fields , firstname ,lastname and mail , also can insert organization fileds name and type , but when i try to insert User_org fields which is foreignkey there is error. -
Trouble with using datepicker in edit form
I have trouble with edit data in django project. Everything is almost ok :) , but if I'm trying edit data my form get all data from database exept date field. I found solution as below and I see datapicker on my edit form but I have to fill in data to this field. Every data in edit form are filled in exept this one. Datapicker for adding records works good. I'm using the same form to add and edit. My forms.py is listed below: from django import forms from .models import Expens, Category class DateInput(forms.DateInput): input_type = 'date' class ExpensForm(forms.ModelForm): class Meta: model = Expens fields = ('name', 'date', 'category', 'value', 'add_description', 'scan') labels = { 'name': 'Nawa wydatku:', 'date': 'Data wydatku:', 'category': 'Kategoria wydatku:', 'value': 'Kwota wydatku:', 'add_description': 'Dodatkowy opis:', 'scan': 'Skan paragonu:', } widgets ={ 'name': forms.TextInput(attrs={'class': 'form-control'}), 'date': DateInput(attrs={'class': 'form-control'}), 'category': forms.Select(attrs={'class': 'form-control'}), 'value': forms.NumberInput(attrs={'class': 'form-control'}), 'add_description': forms.TextInput(attrs={'class': 'form-control'}), 'scan':(), } My html template to this forms is listed below: {% extends 'expenses/index.html' %} {% block tytul %} DATABASE FORMS {% endblock %} {% load bootstrap5 %} {{ form.media }} {% block strona %} {% if new %} <h5>Add record</h5> {% else %} <h5>Edit record</h5> {% … -
Django How to use Postgresql's INSERT INTO ... WHERE conditional insert functionality?
Postgresql has a nice syntax for conditionally inserting: INSERT INTO child (name, parent_id) SELECT :name, :parent_id WHERE EXISTS ( SELECT 1 FROM parent WHERE id = :parent_id AND parent.user_id = :user_id ) In the above example, nothing would be inserted into the child unless the given :user_id was the owner of the parent row. Is it possible to simulate this kind of insert in Django? -
Django prevent users from spamming a view (add to cart)
I have a view (add to cart) that rely on sessions to add or update an item in the cart, And I am using the javascript fetch API so that the hole process is asynchronous, it works fine, but I've noticed that the user can spam the add to cart button/form so what's the best way the prevent that ?, this is my code: def API_View(request): article_slug = request.POST.get('article_slug') if article_slug: try: article = Article.objects.get(slug = article_slug) except Article.DoesNotExist: raise Http404('article does not exist ') my_cart = request.session.get('my_cart',None) if my_cart: if str(article.slug) in my_cart: item = my_cart[str(article.slug)] item['quantity'] += 1 item['status'] = 'updated' request.session.modified = True print(' quantity updated') print(my_cart) else : my_cart[str(article.slug)] ={ 'slug' :str(article.slug), 'quantity' :1, 'status' :'Added' } request.session.modified = True print('new item in cart ') print(my_cart) else: request.session['my_cart'] = { str(article.slug):{ 'slug' :str(article.slug), 'quantity' :1, 'status' :'Added' } } my_cart = request.session['my_cart'] print('first to cart') print(my_cart) return JsonResponse(my_cart,safe=False) -
Are there limits on the reasonable amount of HTML that browsers can handle before they start to slow down in regards to page rendering?
I am working to troubleshoot an issue with my Django formsets implementation. After working with a consultant for a couple hours today...we think it might be related to the amount of HTML that gets generated based on the number of records the formset is processing. Based on 18,000 lines of HTML...the page takes about 15 seconds to load. The same page with fewer records loads much more quickly. We've explored the query thing...and have exhaustively looked at performance metrics on the server side and can't seen anything glaringly sticking out that would be contributing to the perceived slow rendering of the page in the browser. Has anyone else come to this conclusion with their formsets? If so, what potential alternatives are there to resolving the slow page rendering issue? Formsets are great...but it would seem that the browsers have trouble rendering the records when they hit a certain amount? Thanks in advance for any thoughts.