Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
dict object has no attribute
In frontend I use vue js , using axios I sent data to backend.But after clicking submit button I got this error: dict object has no attribute 'invoice_products'. From frontend using axios: this.$http.post('http://127.0.0.1:8000/api/createTest', { invoice_products: this.invoice_products }) This is my json input data {"invoice_products":[{"name":"fgf","price":"56"}]} views.py: @api_view(['POST']) def createTest(request): serializer = TestSerializer(data=request.data.invoice_products) if serializer.is_valid(): serializer.save() return Response(serializer.data) Error: dict object has no attribute 'invoice_products' -
Django project deployment on an offline pc, locally, we don't want to go online
I have a Django project. we cannot go online, is there any way to deploy the project in a client computer just for the client to use there on his pc? no need to go online! user needs to type an address in browser to get the starting page of some other easy path! is it possible? or is there any other way to solve this problem? -
NoReverseMatch at reset_password_complete: Django PasswordResetConfirmView
I am using Django's default password reset views and forms to send an email to the user for them to reset their password via a link in the email. I have most of the development complete but am stuck on one issue. When I receive the email from the local host, I click the link, enter my new password 2 times, hit 'submit' and get this error: Error Message. Below is my code. urls.py """defines URL patterns for users""" from django.urls import path, include, reverse_lazy from django.contrib.auth import views as auth_views from . import views app_name = 'users' urlpatterns = [ # include all default auth urls path('', include('django.contrib.auth.urls')), path('register/', views.register, name='register'), path( 'reset_password/', auth_views.PasswordResetView.as_view( template_name='registration/password_reset.html', success_url=reverse_lazy('users:password_reset_done') ) , name='reset_password' ), path( 'reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='registration/password_reset_form.html', success_url=reverse_lazy('users:password_reset_complete') ), name='password_reset_confirm' ), path( 'password_reset_done/', auth_views.PasswordResetDoneView.as_view( template_name="registration/password_reset_sent.html"), name='password_reset_done' ), path( 'password_reset_complete/', auth_views.PasswordResetCompleteView.as_view( template_name='registration/password_reset_done.html'), name='password_reset_complete' ), path('forgot_username/', views.forgot_username, name="forgot_username"), path('username_retrieval/', views.username_retrieval, name="username_retrieval"), ] As you can see, I am using the namespace 'users' in the success_url variable, however, it seems to work on the reset_password path, but it does not seem to work on the reset/<uidb64>/<token> path. One thing to be aware of is that I have a custom user model in my application. Would … -
(Html,css, JavaScript, python,django) What should I learn to be a full stack developer 2022? Should I follow my current roadmap? [closed]
Currently I m confused which roadmap should I follow to be a full stack web developer. Should I learn mern stack or html,css, JavaScript python Django? Which roadmap is better and high demand for future? Or should I learn php for back end development? -
Django add multiple Users to lobby model
I want to add Users to my players field in the lobby but i dont know how. Every user should be in just one lobby. User Model class GeoUser(AbstractUser): user_score = models.IntegerField(default=0) email = models.EmailField(unique=True) Lobby Model class Lobby(models.Model): lobby_code = models.CharField( max_length=18, unique=True) players = # here i want to add multiple users that should be in the lobby Thanks in advance -
Django regex string validation for emails including international characters
To only allow for international characters in the local part, I am trying to extend the EmailValidator class like this: class EmailValidator(_EmailValidator): """ This is meant to mirror the Django version but override the user_regex to allow for more unicode chars """ user_regex = _lazy_re_compile( r"^\w[a-zA-Z0-9èéàáâãäçêìíîñòóôöäüÖÄÜ\.\-_]", # too vague re.IGNORECASE) Obviously there are some holes in my regex string. Ideally this would adhere to RFC 5322 standards. I have some test emails that I need this to pass: piny@tineapples.com - valid tinä@turner.com - valid pinéapplé@lol.com - valid pinéa@pplé@lol.com - invalid kînda.prétty.ãmazonian1539@pastasauce.co - valid -
how to break the paragraph lines on a live production using django template tag filters?
I have searched for it but couldn't find an example for live server so that's why posting. I am working on a template in django in which I need to break the paragraph lines according to the formate that I have applied in django admin panel. let say I have written the same way as it is here : a paragraph a paragraph example a paragraph a paragraph example a paragraph a paragraph example a paragraph a paragraph example a paragraph a paragraph example so I have applied linebreaks template filter on it and it is working on the development server. When I push the source code on live production, the whole paragraph appears as a single line instead of being displayed with tags. Example on live server: a paragraph a paragraph example<br>a paragraph a paragraph example a paragraph a paragraph example<br>a paragraph a paragraph example a paragraph a paragraph example So I would love to get help from you guys. thanks in advance. -
how to make an Api to create unique URL's for a Form View (Like Googles Forms uniques URLS)
I'm new in Django Rest Framework and Django. I'm trying to make a service Api. The bussiness rule is "If post a field Email, this service return me a unique URL to go to a survey view". But, I'm only can make services with username and Password with AuthToken and only views with static url. Can you Help me?. Thanks in advance!