Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot see blog posts in index.html
I am trying to make a simple blog website. I have created my files and models. The page shows up fine, and the admin works. However, the blogs do not reflect on index.html from the admin page. I included the app in settings.py. All the other pages work, so I don't think the issue is with the file structure. models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse from django.utils import timezone class Todo(models.Model): title = models.CharField(max_length=100) memo = models.TextField(blank=True) created = models.DateTimeField(auto_now_add=True) datecompleted = models.DateTimeField(null=True, blank=True) important = models.BooleanField(default=False) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title class Post(models.Model): title = models.CharField(max_length=200, default='', unique=True) first_name = models.CharField(max_length=50, default='', editable=False) last_name = models.CharField(max_length=50, default='', editable=False) body = models.TextField(default='') def __str__(self): return self.title urls.py (Project) from django.contrib import admin from django.urls import path, include from todo import views urlpatterns = [ path('admin/', admin.site.urls), # Auth path('signup/', views.signupuser, name="signupuser"), path('logout/', views.logoutuser, name='logoutuser'), path('loginuser/', views.loginuser, name='loginuser'), # Todos path('', views.home, name='home'), path('', include('todo.urls')), path('index/', views.index, name="index"), path('detail/', views.detail, name="detail"), path('current/', views.currenttodos, name="currenttodos"), path('create/', views.createtodo, name='createtodo'), path('completed/', views.completedtodos, name="completedtodos"), path('todo/<int:todo_pk>', views.viewtodo, name='viewtodo'), path('todo/<int:todo_pk>/complete', views.completetodo, name='completetodo'), path('todo/<int:todo_pk>/delete', views.deletetodo, name='deletetodo'), path('hotel/', views.hotel, name="hotel"), path('things/', views.things, name="things"), path('restaurant/', views.restaurant, name="restaurant"), path('review/', views.review, name="review"), … -
HTML operators in django
I'm trying to compare actual_time and taken_seconds, but less than operators (<) show in red color, and it actually not compare the numbers.As per image, 6<12, it should say Time taken is higher than actual time of gesturing <h5>Actual time: {{ actual_time }} seconds</h5> <h5>Taken time: {{ taken_time }} seconds ({{ taken_seconds }} seconds)</h5> <h5>Point: {{ point }}</h5> {% if actual_time < taken_seconds %} <div class="alert alert-warning" role="alert"> Time taken is higher than actual time which may lead to fatigue. </div> {% elif actual_time > taken_seconds %} <div class="alert alert-success" role="alert"> Time taken is lower than actual time of gesturing. </div> {% endif %} -
How do I build like functionality using django and djangorestframework?
I'm using Django and DjangoRestFramework to build a social media app, and I am having some issues building the functionality for the like button on the backend. Here is a walkthrough of my current code and the error I am getting: models.py from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Post(models.Model): created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField(blank=True) class Meta: ordering = ('-created_at',) class Like(models.Model): post = models.ForeignKey(Post, related_name='likes', on_delete=models.CASCADE) created_by = models.ForeignKey(User, related_name='likes', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) serializers.py from rest_framework import serializers from apps.feed.models import Post, Like class PostSerializer(serializers.ModelSerializer): class Meta: model = Post read_only_fields = ( "id", "created_at", "created_by", ) fields = ( "id", "created_at", "created_by", "content", ) class LikeSerializer(serializers.ModelSerializer): class Meta: model = Like read_only_fields = ( "id", "created_at", "created_by", ) fields = ( "id", "created_at", "created_by", "post" ) views.py from rest_framework import viewsets from apps.feed.models import Post from apps.feed.serializers import PostSerializer, LikeSerializer from django.contrib.auth import get_user_model from .models import Post User = get_user_model() class PostViewSet(viewsets.ModelViewSet): serializer_class = PostSerializer queryset = Post.objects.all() def perform_create(self, serializer): serializer.save(created_by=self.request.user) def get_queryset(self): return self.queryset.filter(created_by=self.request.user) class LikeViewSet(viewsets.ModelViewSet): serializer_class = LikeSerializer def perform_create(self, serializer): serializer.save(created_by=self.request.user) The error when I press the like button: # This is … -
display images in select option for selection -Django Python
I am working on a PRoject and I am stuck on order page. Here, I want to display list of product images in options tag so that a user can select one image from all or can upload an image functionality of uploading image is working correctly but the selection is not working. I want to show images to user so that user can select one of them. models.py class Product(models.Model): prod_ID = models.AutoField("Product ID", primary_key=True) prod_Name = models.CharField("Product Name", max_length=30, null=False) prod_Desc = models.CharField("Product Description", max_length=2000, null=False) prod_Price = models.IntegerField("Product Price/Piece", default=0.00) prod_img = models.ImageField("Product Image", null=True) class ImageTemplate(models.Model): temp_id = models.AutoField("Template ID", primary_key=True, auto_created=True) temp_img = models.ImageField("Template Image", null=False) class ImageTemplateProductMapping(models.Model): imageTemp_p_map_id = models.AutoField("Template Image & Product Map ID", primary_key=True, auto_created=True) temp_id = models.ForeignKey(ImageTemplate, null=False, on_delete=models.CASCADE, verbose_name="Image Template ID") prod_id = models.ForeignKey(Product, null=False, on_delete=models.CASCADE, verbose_name="Product Id") views.py def order(request, id): products = Product.objects.all() ImageTemplateProductsList = [] try: ImageTemplateProductsMap = ImageTemplateProductMapping.objects.filter(prod_id=id) ImageTemplateProductsList = [data.temp_id.temp_img for data in ImageTemplateProductsMap] except AttributeError: pass context = {'products': products, "ImageTemplateProductsList": ImageTemplateProductsList } return render(request, 'user/order.html', context) order.html {% extends 'user/layout/userMaster.html' %} {% block title %}Order{% endblock %} {% block css %} form { position:relative; } .tasksInput { margin-right:150px; } label { vertical-align: top; … -
How to delete django dynamic formset with java script - issue with index?
In my template i'm using a formset to add a "Raum"-form dynamic. In each row of my table, there is a button "delete row", so that i can delete the row again. the java script code is as far as i can say is working quite well... Adding and saving the forms works fine. Also deleting with the java script code works fine. Even when i delete the last row of the table, saving the forms works fine. But when f.e. i add 3 rows (rooms), row1-row2 and row3, and i delete row 1 or row 2, i can not save my forms, because i think in view.py the is_valid method = false... maybe i have to update some kind of index of my forms??? and how ?? any help is really apprecheated... html template for adding rooms with the table and forms: <table id="tableHeadToModify" class="table table-bordered"> <thead class="hg-rot schrift-weiss"> <tr> <th colspan="2">Räume</th> </tr> {% for raum in raum_formset %} {% if forloop.first %} <tr> <th>{{ raum.name.label_tag }}</th> <th>{{ raum.name.label_tag }}</th> </tr> {% endif %} {% endfor %} </thead> <tbody id="tableToModify"> {{raum_formset.management_form}} {% for raum in raum_formset %} <tr id="rowToClone"> <td> {{ raum.name }} </td> <td><button type="button" value="Delete" onclick="deleteRow(this)"></td> </tr> … -
How to get username at end of url using slug
I'm trying to get the users username at the end of the 'my-profile' url , I have used autoslug on url ("users/") and this is working fine for 'profile_view' , but it's not working with 'my_profile' , can you tell me what I'm doing wrong. At the moment i'm getting error: NoReverseMatch at / Reverse for 'my_profile' with no arguments not found. 1 pattern(s) tried: ['my\-profile/(?P[^/]+)$'] urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('feed.urls')), path('users/', user_views.users_list, name='users_list'), path('users/<slug>/', user_views.profile_view, name='profile_view'), path('friends/', user_views.friend_list, name='friend_list'), path('users/friend-request/send/<str:username>/', user_views.send_friend_request, name='send_friend_request'), path('users/friend-request/cancel/<str:username>/', user_views.cancel_friend_request, name='cancel_friend_request'), path('users/friend-request/accept/<str:username>/', user_views.accept_friend_request, name='accept_friend_request'), path('users/friend-request/delete/<int:id>/', user_views.delete_friend_request, name='delete_friend_request'), path('users/friend/delete/<int:id>/', user_views.delete_friend, name='delete_friend'), path('edit-profile/', user_views.edit_profile, name='edit_profile'), path('my-profile/<slug>', user_views.my_profile, name='my_profile'), path('search_users/', user_views.search_users, name='search_users'), ] models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.png', upload_to='profile_pics') slug = AutoSlugField(populate_from='user') bio = models.CharField(max_length=255, blank=True) friends = models.ManyToManyField('Profile', blank=True) def __str__(self): return str(self.user.username) def get_absolute_url(self): return "/users/{}".format(self.slug) views.py @login_required def profile_view(request, slug): p = Profile.objects.filter(slug=slug).first() u = p.user sent_friend_requests = FriendRequest.objects.filter(from_user=p.user) rec_friend_requests = FriendRequest.objects.filter(to_user=p.user) user_posts = Post.objects.filter(user_name=u) friends = p.friends.all() # is this user our friend button_status = 'none' if p not in request.user.profile.friends.all(): button_status = 'not_friend' # if we have sent him a friend request if len(FriendRequest.objects.filter( from_user=request.user).filter(to_user=p.user)) == 1: button_status = 'friend_request_sent' # if we have received … -
How are you able to extract a count within a StructValue in Django framework?
My html code in Django is {{ self }} and it will output as follows StructValue([('Title', 'Product 30'), ('Image', None), ('Cards', [StructValue([('Document', <Document: blah>)])])]) How am I able to manipulate this HTML to get the number of documents within {{ self.cards }}? For example i have tried {{ self.cards.document.count }} with no success. Am I even just looking at this the wrong way? -
How to point django form to pk?
I am trying to make a form that is dynamically selected by a DetailView object. I want to click the DetailView link and be taken to a form whose primary key is the same as the primary key from my detail view. When I attempt to do this I get an error. How can I do this? Is their a prebuilt library that will assist me? My Model: ''' class MemberStudent(models.Model): instructor = models.ForeignKey(Teachers, on_delete=models.CASCADE) name = models.CharField(max_length=50, default="Doe") age = models.IntegerField(default=99) def __str__(self): return self.name def get_absolute_url(self): return reverse('student_detail', args=[str(self.id)]) class BehaviorGrade(models.Model): SEVERITY = [ ('Bad','Bad Behavior'), ('Good','Good Behavior'), ('Danger','Dangerous'), ] LETTER_GRADE = [ ('A','A'), ('B','B'), ('F','F'), ] studentName = models.ForeignKey(MemberStudent, on_delete=models.CASCADE) #need a link to student name eventGrade = models.CharField(max_length=1, choices=LETTER_GRADE) eventSeverity = models.CharField(max_length=15, choices=SEVERITY) eventTitle = models.CharField(max_length=15) eventDescription = models.TextField() def __str__(self): return self.eventTitle ''' My Views: ''' class StudentDetailView(FormMixin,DetailView): model = MemberStudent template_name = 'student_detail.html' form_class = BehaviorForm def get_success_url(self): return reverse('student_detail', kwargs={'pk':self.object.pk}) def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): form.save() return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): return super().form_valid(form) ''' my forms.py: ''' class BehaviorForm(ModelForm): class Meta: model = BehaviorGrade fields = ['eventGrade', 'eventSeverity','eventTitle', 'eventDescription'] ''' my url: … -
How to join querysets and do some calculation on some of them
I need advice how should I implement view function which for now works but I think there is an easier way to do it. Lets say that user can add a meal for specific day it might be 1 meal or 2 or whatever he choose, in specific meal an author can set how many portions are in that meal and user can choose how many portions he would like to add from that specific meal. Each meal contains some ingredients each ingredient contain information about calories etc. For example: User Foo created Meal Scrambled Eggs with Ingredients 200g Eggs(100kcal 10g proteins etc) and 100g Onions(20kcal 2g proteins etc) and Portions 2 User Bar created Meal Spaghetti with Ingredients 200g Pasta(300kcal 5g proteins etc) 400g Tomatoes Sauce(80kcal 8g proteins etc) 300g Meat(350kcal 45g proteins etc), Portions 3 User C want to add those meals to his day but only choose 1 portion from each meal. And there is a question how I can get Ingredients and nutritional values depended of chosen portions for each meal ? I tried to do this in a way which is showed in my views but I am sure that there is an easier way … -
The problem is that the user profile change form is always valid in Django
I have two different forms of a model in a template I change the user's photo with one form and edit the user's text profile with another form The model (profile) is a one-to-one relationship with the main Django user But I have a problem with the user photo change form When clicking on the user profile edit form which is the profile model (for text changes) The photo change form is also called and is always valid My forms are from the Django form model Definitely the main problem is the image change form, but I do not know which part of the code has a problem. I send the values to the server with Ajax. Below I will display the codes and output to convey the concept easier If you do not understand my problem, I can explain more to you, just give me your email address so that I can contact you. Thank you. Output View def edit_user_view(request, pk): user = get_object_or_404(User, pk=pk) c_default_user_edit_form = default_user_edit_form( request.POST or None, initial=vars(user), instance=user ) c_user_image_editing_form = user_image_editing_form( request.POST or None, request.FILES or None, instance=user.profile ) c_user_information_editing_form = user_information_editing_form( request.POST or None, initial=vars(user.profile), instance=user.profile, ) if c_default_user_edit_form.is_valid(): print("default user") c_default_user_edit_form.save() … -
Django query possibly at the views.py
I am getting the following error: TypeError: Choice() got an unexpected keyword argument 'skill' Here is my code below: def create_choice(request): if request.is_ajax(): skill = request.POST.get('skill') print(skill) skill_obj = Skill.objects.get(name=skill) price = request.POST.get('price') print(price) price_obj = Price.objects.get(name=price, skill__name=skill_obj.name) Choice.objects.create(skill=skill_obj, price=price_obj) return JsonResponse({'created':True}) return JsonResponse({'created':False}, safe=False) -
Blog on Django, querysets for fetch logged in user's posts
I'm building a blog on Django and know i have to make a personal page for see all the posts published by the user we're logged in now. I'm using some querysets so. Her my code my models.py from django.db import models from django.conf import settings from django.utils import timezone class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title Here my forms.py from django.contrib.auth.forms import UserCreationForm from django import forms from django.contrib.auth.models import User from .models import Post class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username','email','password1','password2','user_permissions','is_staff','date_joined'] class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'text', 'author'] And that's the view which is gonna filter the posts in base of the logged user from django.contrib.auth.models import User from django.contrib import messages from django.contrib.auth import authenticate,login,logout from django.contrib.auth.decorators import login_required from django.utils import timezone from .forms import CreateUserForm from .models import Post from .forms import PostForm def user_data(request, pk): user_data = User.objects.get(pk=pk) posts = user_data.post_set.filter(author=user_data) context = {'user_data':user_data, 'posts':posts} return render(request, 'account/user_data.html', context) #So it returns me just the user data like name, email or date_joined but not … -
django_elasticsearch_dsl_drf search in text field with space returns null
I have the following index in my Elasticsearch: "mappings": { "properties": { "content": { "type": "text" }, . . . When I use kibana console searching in content field by a value such This is, It return all documents with phrase This is in the content, but using django_elasticsearch_dsl_drf (and django rest framework) it returns nothing and the search only works by values with no spaces, I mean If i search for the word This it returns the results as wished. My document: @INDEX.doc_type class PostDocument(Document): content = fields.TextField() ... my serializer: class PostDocumentSerializer(DocumentSerializer): """Serializer for the Post document.""" content = serializers.CharField() ... my viewset: class PostDocumentView(DocumentViewSet): document = PostDocument serializer_class = PostDocumentSerializer pagination_class = PageNumberPagination filter_backends = [ FilteringFilterBackend, IdsFilterBackend, OrderingFilterBackend, DefaultOrderingFilterBackend, SearchFilterBackend, SuggesterFilterBackend, ] # Define search fields search_fields = ( 'content', ... ) filter_fields = { 'content': { 'field': 'content', 'lookups': [ LOOKUP_QUERY_CONTAINS, LOOKUP_QUERY_IN ] }, } and the URL to test is: http://127.0.0.1:8000/social_networks/posts_search/?format=json&page=1=&content=This is -
CRITICAL WORKER TIMEOUT in Gunicorn
I have written a Flask application and run the python code from terminal. python xxx.py Then I enter a curl command into another terminal and print outs of my code appear in the Flask terminal. After that, I created a wsgi.py file for Gunicorn in the same folder and run it from terminal. gunicorn --bind localhost:5101 wsgi:xxx Then I enter the same curl command from another terminal to access the functions in Flask app using Gunicorn. However, the Gunicorn terminal prints [2021-02-16 13:57:04 +0100] [1043] [CRITICAL] WORKER TIMEOUT (pid:1224) [2021-02-16 13:57:04 +0100] [1224] [INFO] Worker exiting (pid: 1224) and I cannot get the results from my desired function in Flask. Can someone guide me what am I doing wrong? Thanks. -
My Css is not being rendered for the django rest framework access page but works fine for the other pages in my site when using apache server
The css gets rendered properly when I use the django development server I checked the static files and the required css files have been collected in the folder as well Below is the apache server .conf file me_buildout_xmeme is the repo name memev2 is the project name <VirtualHost *:80 *:8080> ServerAdmin webmaster@example.com DocumentRoot /home/ubuntu/django/me_buildout_xmeme ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/ubuntu/django/me_buildout_xmeme/static <Directory /home/ubuntu/django/me_buildout_xmeme/static> Require all granted </Directory> <Directory /home/ubuntu/django/me_buildout_xmeme/memev2> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess memev2 python-path=/home/ubuntu/django/me_buildout_xmeme python-home=/home/ubuntu/django/myprojectenv WSGIProcessGroup memev2 WSGIScriptAlias / /home/ubuntu/django/me_buildout_xmeme/memev2/wsgi.py </VirtualHost> This refers to the settings.py settings STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static_collected') # STATIC_ROOT='static' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) -
Django behaving strangely on updating a JsonField using Model objects
Since my code is pretty big, I have not copied it entirely. Instead added whatever i feel is required. I have a Model class class SomeModel(models.Model): id = models.BigAutoField(primary_key=True) policy = JSONField(null=True) Initially the value in policy is in format like this: [ { "type": "Bed", "policy": { "details": [ { "from": "2021-04-17T00:00:00", "currency": "INR", "flat_fee": 3000 }, { "from": "2021-04-18T00:00:00", "currency": "INR", "flat_fee": 4000 } ], "under_flag": false } } ] Then I'm updating the data within details field of the object using following function: def _update_policy(some_model_object): policy_list = some_model_object.policy if policy_list: for index, policy_data in enumerate(policy_list): policy = policy_data.get('policy') details = policy.pop('details') final_details = [] for i, detail in enumerate(details): detail['new_fee'] = #some computation detail['id'] = i + 1 final_details.append(detail) policy['details'] = final_details print('policy', policy) print('policy_list', policy_list) some_model_object.policy = policy_list self.itinerary_booking_details.save() Now both the print statements show the update dictionary with the new_fee field added. But the same is not reflected in DB after save(). Question Summary: I'm updating a JSONField in django, and saving the model object. The print statement before save function is called, shows that the variable is updated. But after assigning and saving the same, it doesn't reflect in DB. I'm using Django 3.0.5, … -
How do I dynamically set value to Many2Many field?
Is it possible to use a variable to get the instance of the m2m model-field and then use .set()? I know that this how we can use setattr to use a variable to set a value to a class: myfield = "fieldname" mylist = ["data"] setattr(model, myfield, mylist) And that we set value to a ManyToManyField by doing: mylist = ["data"] model.fieldname.set(mylist) Question: Is it possible to use a variable to get the instance of the m2m model-field and then use .set()? Something like (this doesn't work): myfield = "fieldname" mylist = ["data"] getattr(model, myfield).set(mylist) # throws AttributeError: 'list' object has no attribute 'set' TYIA! -
Django rest framework websockets auto update
I am using django rest framework for my API,and vue for frontend, and, it is possible to auto update my frontend state when I changed something ?Its totally basic vue and django code, just for example Vue <template> <div> <div class="numbers">{{ state.numbers }}</div> Number pk <input type="text" v-model="state.pk" /> Number value <input type="text" v-model="state.inputValue" /> <button v-on:click="changeNumber">change !</button> </div> </template> <script> import axios from "axios"; import { reactive, onMounted } from "vue"; export default { name: "HelloWorld", setup() { const state = reactive({ numbers: [], inputValue: 1, pk: 1, }); function changeNumber() { const data = { number: state.inputValue, }; console.log(data); axios.patch(`http://127.0.0.1:8000/api/number-update/${state.pk}/`, data); } onMounted(() => { axios .get("http://127.0.0.1:8000/api/numbers-list/") .then((res) => (state.numbers = res.data)); }); return { changeNumber, state, }; }, }; </script> How it is in browser and I want to, when I click change button, auto update backend data,without refreshing. Backend Serializers.py from rest_framework import serializers from .models import Number class NumberSerializer(serializers.ModelSerializer): class Meta: model = Number fields = '__all__' Views.py from django.shortcuts import render from .serializers import NumberSerializer from rest_framework import generics from .models import Number class NumbersList(generics.ListAPIView): queryset = Number.objects.all() serializer_class = NumberSerializer class NumberUpdate(generics.UpdateAPIView): queryset = Number.objects.all() serializer_class = NumberSerializer Urls.py from django.urls import path … -
Ajax request cannot access the URL in Django. I have a problem with an integer( the id)
Hello everyone! I'm working on an app for patients using Django. I tried to get all the details about a patient and display them on a new panel. When the user presses a button I use the patient's id. When I try to put this id in ajax's URL I receive an error "NoReverseMatch". I don't know how to solve it. Any help is welcome. Sorry for the indentation, but this is Atom :)) I have two ajax requests. The first one is functional( here I display all patients' names in a table, for every patient I attach a button named "Details". When the user clicks the "Details" button for a patient I want to display all data about this person on a new panel using a href to the second ajax). I have a "Delete" button too, but it's functional, the "Details" is the problem here. views.py def getPatientDetails(request, id): currentPatient = Patient.objects.get(id=id) return JsonResponse({"patient":currentPatient}) urls.py for this function path('getPatientDetails/<int:id>', getPatientDetails, name='getPatientDetails'), Here is the html template This is the first ajax, which is functional <script> $(document).ready(function(){ $.ajax({ type:'GET', url: "{% url 'getPatients' %}", success: function(response){ $("#displayPatients").empty(); for(var key in response.patients) { var temp = "<tr><td>"+response.patients[key].firstName+"</td><td>"+response.patients[key].lastName+"</td><td>"+response.patients[key].phone+"</td><td><a href='getPatientDetails/"+response.patients[key].id+"'><button class='detailsButton outline-text'>Details</button></a><a … -
SQLite 3.8.3 or later is required (found 3.7.17). in centos
run : python manage.py runserver raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version) django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.7.17). -
Python Negative time difference
I am new to django. I want to calculate the total time. My model counts the time difference - and stores, the view counts the time sum. It works. But if the time difference is negative(01:00 - 21:00), then I get an error(time data '-1 day, 4:00:00' does not match format '%H:%M:%S'). according to the idea it should be 4:00 o'clock I suppose that you need to save time not explicitly, but I do not understand how to do it. Or do you need to use something else? Models.py class Trip(models.Model): ... start_work = models.TimeField(verbose_name='Начало работы') finish_work = models.TimeField(verbose_name='Окончание работы') hours_worked = models.CharField(verbose_name='Отработано часов', max_length=50, blank=True) ... @property def hours_work(self): result = datetime.combine(date.today(), self.finish_work) - datetime.combine(date.today(), self.start_work) hours_work1 = str(result).rsplit(':', 1)[0] hours_worked = hours_work1 return hours_worked def save(self, *args, **kwargs, ): self.hours_worked = self.hours_work super(Trip, self).save(*args, **kwargs) wiews.py total_time = timedelta(hours=0, minutes=0) me = trip.values_list('hours_worked') sum_hour = 0 for el in me: for i in el: time = datetime.strptime(i, "%H:%M:%S") t1 = timedelta(hours=time.hour, minutes=time.minute) total_time = total_time + t1 sum_hour = str(total_time).rsplit(':', 1)[0] -
How to write OR condition in Django ORM for same values in two different columns
for the below class I need to write a django query in such way that value "John" should be passed for both Ename and HOD with an OR condition I need a DJANGO query to display the records with condition (Ename="John" or HOD="John") AND Country="UK" class Employee(models.Model): Ename=models.CharField(max_length=30) HOD = models.CharField(max_length=30) Dep = models.FloatField() Email = models.CharField(max_length=35) -
How to find a clicked element in django?
Onn my Django webpage I have multiple list items which all have onclick listener. I need python code to find the element that was clicked. -
Sorting content to reverse during implementation of infinity scroll in Django
I'm an introducer of Django. Like Instagram, I'm trying to make pictures or videos come out when they go down. I implemented pagination through infinite scrolling, but there was a problem that the posts that were previously reprinted and displayed in the latest order were not sorted in the latest order. There are 10 posts (the higher the number, the more recent), and paginated_by is set to 4. originally, it was 10 9 8 7 6 5 4 3 2 1, but when I applied the infinite scroll, I could find the phenomenon that was reverted in the order of 4 3 2 1 8 7 6 5 10 9. I'd like to apply the infinite scoll in order of 109 8 7 6 5 4 3 2 1. Please help me, thank you here are my codes. models.py class Video(models.Model): status_choices = { ('before eating', '먹기전'), ('eating', '먹는중'), } restaurant = models.CharField(max_length = 128, verbose_name = '가게이름') foodname = models.CharField(max_length= 128, verbose_name= '음식이름') file = models.FileField() price = models.PositiveIntegerField(default=0) status = models.CharField(max_length=80, choices= status_choices, null=True) distance = models.PositiveIntegerField(default=0, verbose_name='거리') title = models.CharField(max_length= 128, verbose_name= '제목', default= '모르겠어요') author = models.ForeignKey('user.meokda_user', on_delete = models.CASCADE, verbose_name = '작성자', null = True … -
Kali linux cant import modules that i created
thanks for your time. i've started to work on kali linux and don't know why i'm not beeing able to import files. By using python manage.py every thing works fine, although when trying to run a file by it self i get or : from .models import Player ImportError: attempted relative import with no known parent package``` or from winners.models import Player ``` ModuleNotFoundError: No module named 'winners' I've tried to reset the ambient variable DJANGO_SETTINGS_MODULE DJANGO_SETTINGS_MODULE=olympic.settings tryed to add the path manually trough sys.path, tryed every possible way of import. i guess is something i configured wrong. thats my sys.path output: ['/home/kali/.virtualenvs/celero/olympic/winners', '/usr/lib/python39.zip', '/usr/lib/python3.9', '/usr/lib/python3.9/lib-dynload', '/home/kali/.virtualenvs/celero/lib/python3.9/site-packages']