Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add custom css to Bootstrap/Django files
I am trying to add a custom css snippet into my code for my homepage(index.html)but am new to bootstrap/css and not sure which file to add the code to. So far, I've tried adding the snippet to a custom.css file within the same directory as my html files but nothing is changing. Would I instead add this to index.html file? Can you even add css to an html file? Example of code snippet im trying to add: body { background: url('https://source.unsplash.com/twukN12EN7c/1920x1080') no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; background-size: cover; -o-background-size: cover; } -
Django: how to specify `include_blank=False` in `modelform_factory` using `formfield_callback`?
I am using the django.forms.modelform_factory() function. Some of the database fields are IntegerFields with choices, so Django defaults to using a django.forms.TypedChoiceField that has a blank choice ("--------------"). I'm using the RadioSelect widget, so it's redundant to have a blank choice. How do I get rid of the blank choice? (I'm answering my own question, but of course if you have a better answer, feel free to share!) -
Unable to add two foreign keys to the user model in django
I have a user model which I have extended to store extra information. Now I have a department table which has two keys(foreign) which will be related to the columns in the user table. But I am getting an error. This is what I have tried models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Profile(models.Model): STATUS_CHOICES = ( (1, ("Permanent")), (2, ("Temporary")), ) GENDER_CHOICES = ( (1, ("Male")), (2, ("Female")), (3, ("Not Specified")) ) user = models.OneToOneField(User, on_delete=models.CASCADE) emp_type = models.IntegerField(choices=STATUS_CHOICES, default=1) contact = models.CharField(max_length=13, blank=True) whatsapp = models.CharField(max_length=13, blank=True) gender = models.IntegerField(choices=GENDER_CHOICES, default=3) avatar = models.ImageField(upload_to='users/images', default='users/images/default.jpg') manager_username = models.ForeignKey(User, blank=True, null=True, related_name='usernames', on_delete=models.DO_NOTHING) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() class Department(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=20, unique=True) manager = models.ForeignKey(User, blank=True, null=True, related_name='manager_usernames', on_delete=models.DO_NOTHING) tech_lead = models.ForeignKey(User, blank=True, null=True, related_name='usernames', on_delete=models.DO_NOTHING) Error message ERRORS: users.Department.tech_lead: (fields.E304) Reverse accessor for 'Department.tech_lead' clashes with reverse accessor for 'Profile.manager_username'. HINT: Add or change a related_name argument to the definition for 'Department.tech_lead' or 'Profile.manager_username'. users.Department.tech_lead: (fields.E305) Reverse query name for 'Department.tech_lead' … -
Android device can not connect Django websocket
I built an app with a chat function using Django channels, everything works fine, I can connect to it from iOS simulator, iOs Device, even with an Android simulator, but when I launch it on an actual android device (Huawei Pro) It seems it does not want to connect. What can cause an issue like this? Should I implement something in my Android code or is it a specific problem with Huawei? I use JavaScript's WebSocket to connect to it. -
Django Rest Framework AttributeError when trying to serializering table that acts many to many relation
i am facing an error that says : Got AttributeError when attempting to get a value for field name on serializer productsserializer. The serializer field might be named incorrectly and not match any attribute or key on the branch_products instance. Original exception text was: 'branch_products' object has no attribute 'name'. my models: class products(models.Model): name=models.CharField(max_length=50) Barcode=models.IntegerField() price=models.FloatField(null=True) prev_price=models.FloatField(blank=True,null=True) category=models.ForeignKey(category,on_delete=models.CASCADE) description=models.TextField() image=models.ImageField(upload_to='pics',default='') def __str__(self): return self.name class branch(models.Model): QR_code=models.CharField(max_length=30) def __str__(self): return self.QR_code class branch_products(models.Model): product=models.ForeignKey(products,on_delete=models.CASCADE) branch=models.ForeignKey(branch,on_delete=models.CASCADE) quantity=models.IntegerField() and this is my serializers: class branchserializer(serializers.ModelSerializer): class Meta: model=branch fields=['QR_code','id'] class productsserializer(serializers.ModelSerializer): category=serializers.SerializerMethodField() class Meta: model=products fields=['id','name','Barcode','price','prev_price','description','image','category'] def get_category(self,obj): return categoryserializer(obj).data class productbranchserializer(serializers.ModelSerializer): branch=serializers.SerializerMethodField() product=serializers.SerializerMethodField() class Meta: model=branch_products fields=('product','branch','quantity','id') def get_branch(self,obj): return branchserializer(obj).data def get_product(self,obj): return productsserializer(obj).data it seems that it takes a value from wrong place or wrong Serializer -
django_graphene looking for package "six" in the wrong place?
I'm trying to use graphene-django, and a having some issues with the "six" package. It's installed, but it's installed as its own package, and graphene-django seems to be expecting it under django.utils File "C:\Users\mjnic\.virtualenvs\phoenix-demo-C42C_PgQ\lib\site-packages\graphene_django\settings.py", line 18, in <module> from django.utils import six ImportError: cannot import name 'six' from 'django.utils' (C:\Users\mjnic\.virtualenvs\phoenix-demo-C42C_PgQ\lib\site-packages\django\utils\__init__.py) I've checked the source for graphene_django and in the settings.py it seems to be looking specifically at the django path. This module provides the `graphene_settings` object, that is used to access Graphene settings, checking for user settings first, then falling back to the defaults. """ from __future__ import unicode_literals from django.conf import settings from django.test.signals import setting_changed from django.utils import six I'm using pipenv to manage my environment, and I've uninstalled and reinstalled six, and the various graphene packages several times now trying to sort this out, to no avail. So how can I either move the installation of six so that it's located at django.utils.six, alternatively change the setup so that graphene-django is looking at the currently installed location instead (doesn't seem possible looking at the source)? -
Django test ignore a part of the response
doctest has ellipsis (three dots) which can be used to ignore a part of the string while running a test, for example in this case for a JSON string the value of the field id will be ignored: { id: ..., name: "John" } Is there something convenient like that when writing an application using Django + Django Rest Framework without using explicit regular expressions? -
PythonAnywhere: django.db.utils.OperationalError: no such table:
I am deploying a project on PythonAnywhere. I am using sqlite database. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'mydatabase.db', } } When makemigrations starts, the file mydatabase.db is created (its size is 0 bytes) in root of the project, but I get an error - django.db.utils.OperationalError: no such table: ... -
Is there a way to iterate throw annotate sum query in django
Is there a way to make that for loop in query emp_id = 1 qs= Employee.objects.get(id = emp_id ) InitialSalary =qs.Salary qs1 = AnnualIncrease.objects.filter(employee_name_id = emp_id, startDate__range =(qs.Emp_date,timezone.now()) ).exclude(approveDate=None, submitDate =None).order_by('employee_name_id', 'startDate' ) ActualSalary = InitialSalary for x in qs1: ActualSalary = float(ActualSalary) + (float(ActualSalary)* float(x.AnnualIncreasePercent)/100) + float(x.AnnualIncreaseDecimal) I already try the below and it work but this don't get the needed result of course qss1 = AnnualIncrease.objects.filter( startDate__lte= timezone.now() ).order_by('employee_name_id', 'startDate' ).values( 'employee_name_id', 'employee_name__Salary' ).exclude( approveDate=None, submitDate =None).annotate( ActualSlary = Sum(ExpressionWrapper( F('employee_name__Salary')+ (F('employee_name__Salary')*Coalesce(F('AnnualIncreasePercent'),Value(0))/Value(100))+ Coalesce(F('AnnualIncreaseDecimal'),Value(0)) ,output_field = FloatField()) )) -
python logic for getting output from different variables
id subid num cd val o/p 123 333 2546 1 3 123 222 6545 1 2 123 545 Z3245 1 5 456 784 5423 1 6 456 478 Z3245 1 2 456 470 5623 1 8 I have defined the above table as a class and the columns as an object in Django Models.py file. I'm passing all the above variables/columns as a one by one value by 'id' column into a function for each 'id' specific. I will define a list x = [6545, 5423] before, which comes from num column. For eg: id = 123 (It is associated with three subid) subid = I have three values which i need to iterate it and get its specific num column values. num = if 'num' value is exists in 'x' list as mentioned above from specific id then, 'val' column value which is 5 for 'Z3245' should be printed as o/p value. so o/p value should come as 5. Rest of the o/p values can be ignored. similarly for 456 id the z3245 value should be 2 as o/p, 5423 existed in x list above for specific id. cd = All these should be happened under the condition if … -
Moved legacy classic asp web site to django app but having trouble with django URL redirect app - old URLs with parameters get 500 error
I moved a 20 year old classic asp web site to a django app recently. Google Search Console is showing 500 errors for tons of very old URLS with parameters like /somefile.asp?ID=1234&name=some-name. Most of these URLS I don't even care about - they are really old but would rather they result in 404 than 500. Some do relate to newer content and in theory I could redirect to new django pages but when I try to redirect them using the django redirect app, the site shows 500 errors - like the ? either stops the pages from ever getting to the redirect middleware or the redirect app doesn't like the "?". How can I redirect these urls so I don't get 500 errors? Is there a way in a view to say: if the full url path is x redirect to full url path y I have looked all over stack overflow and elsewhere and can't find this exact problem or a way to write a view like this. I did try the solution here (exactly) because it seems closest to my issue, but it did not work for me for this exact problem: Django's redirects app doesn't work with … -
How to implement direct messaging in Django?
I'm trying to figure out how to allow my users to direct message each other. The only caveat is that messaging is only allowed while a transaction between the two users is in progress, so there will be one thread of messages for each Transaction. I have a Transaction model, and at first I was thinking I could add a field to the Transaction model that would be an array of message objects, but there does not seem to be a model field for that (but perhaps I'm wrong). Instead, should I create a separate model, i.e. Thread, for the thread of messages related to the transaction? Thanks for any advice. -
Django-forms: Raise forms.ValidationError not working
I am beginner in Django and recently studied form-validation. I implemented the code but was unable to raise ValidationError for some constraints. Here are my subsequent file content. forms.py from django import forms from django.core import validators class formClass(forms.Form): name = forms.CharField(max_length=128) email = forms.EmailField(max_length=256) text = forms.CharField(widget=forms.Textarea) catchBot = forms.CharField(required=False, widget=forms.HiddenInput, validators=[validators.MaxLengthValidator(0)]) def clean(self): cleaned_data = super(formClass, self).clean() t = self.cleaned_data.get('name') if t[0].lower() != 'd': raise forms.ValidationError('Name must start from d.') return cleaned_data views.py from django.shortcuts import render from formApp import forms from django.http import HttpResponseRedirect def formNameView(request): formObj = forms.formClass() formDict = {'form': formObj} if request.method == 'POST': formObj = forms.formClass(request.POST) if formObj.is_valid(): # SOME CODE print("NAME: " + formObj.cleaned_data['name']) print("EMAIL: " + formObj.cleaned_data['email']) return HttpResponseRedirect('/users') return render(request, 'formApp/forms.html', context=formDict) My valid input works great, but it doesn't happen with my invalid input. for example: if name = 'Alex', it should raise an error. But it doesn't. Could someone please help me in it? -
Set up connection between azure redis cache and azure kubernetes service
Please help me in setting up the connection between azure redis cache and aks. I am building an application where I would like to deploy it in aks and add redis as a service. -
django-elasticsearch-dsl with AWS elasticsearch
I'm trying to use AWS ElasticBeanStalk to deploy a Django app using django-elasticsearch-dsl and I need to run ./manage.py search_index --rebuild the first time I load it. So within my container commands I've got: 03_elasticsearch: command: "source /opt/python/run/venv/bin/activate && ./src/manage.py search_index --rebuild" The problem is it is waiting for a n/Y to the question Are you sure you want to delete the 'hjsm-local' indexes? [n/Y]: How do I rebuild my indecies? -
How to get the a value related in a Foreign key Django
Im trying to get the value from an attribute related when I select something in a foreing key, and then I want to put that value in a new field, this is the table when I want to do this: table I know I need to implement javascript but im new in django and I dont know how to get the values and then set it in the new field. My Models: class Producto(models.Model): producto = models.CharField(max_length=100) descripcion = models.CharField(max_length=200) precio = models.DecimalField(max_digits=10, decimal_places=2, default=0) LOAN_CATEGORIA = ( ('p', 'Platillo'), ('b', 'Bebida'), ) categoria = models.CharField(max_length=1, choices=LOAN_CATEGORIA, blank=False, default='p', help_text='Categoria del Producto') imagen = models.ImageField(upload_to='photos') def get_absolute_url(self): return reverse('control:producto-detail', args=[str(self.id)]) def __str__(self): return self.producto class Pedido(models.Model): total = models.DecimalField(max_digits=10, decimal_places=2, default=0) fecha = models.DateField(default=datetime.now, null=True, blank=True) estado = models.CharField(max_length=20, default='Pendiente') def get_absolute_url(self): return reverse('control:pedido-detail', args=[str(self.id)]) def __str__(self): return "[" + str(self.id) + "][" + str(self.fecha) + "] " class DetallePedido(models.Model): pedido = models.ForeignKey(Pedido, db_column='pedido_id', on_delete=models.SET_NULL, null=True) producto = models.ForeignKey(Producto, db_column='producto_id', on_delete=models.SET_NULL, null=True, verbose_name='Productos') cantidad = models.DecimalField(max_digits=10, decimal_places=0, default=1) precio = models.DecimalField(max_digits=10, decimal_places=0, default=1) Here in "DetallePedido" is where I want to store the price value based in the selected "Producto" -
Create/Update operations with nested serializers
I, as a newbie Django developer, am trying to build a RESTful API for a mobile app. I've took over an existing project and previous developers have used Django REST Framework. Super cool package, easy to work with so far. Except for one thing... There is this problem when I want to create new resources, which happen to have nested serializers. I'm not great on explaining software issues with words, so here is the simplified version of my case: class UserSerializer(serializers.ModelSerializer): company = CompanySerializer() # other props and functions are unrelated class CompanySerializer(serializers.ModelSerializer): # props and functions are unrelated Now with this structure, GET /users and GET /users/{id} endpoints work great and I get the results I expect. But with POST /users and PATCH /users/{id} I get a response that says I need to provide an object for company prop and it should resemble a Company object with all the required props, so that it can create the company too. And I'm sure it tries to create a new company because I've tried sending { company: { id: 1 } } and it simply ignores the ID and requires a name to create a new one. This is obviously not … -
ModelForm : validate UniqueConstraint when one of the fields is not included in the form
I have a model called Note. Each Note belongs to a User. A Note must have a code that is unique among all the Notes of the User it belongs to, hence the UniqueConstraint. NoteForm does not include the field owner, since -obviously- I want it to be filled automatically (the user should not be able to choose that). """core/models.py""" from django.db import models from django.contrib.auth.models import User class Note(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='note') code = models.CharField(max_length=60) ... class Meta: constraints = [ models.UniqueConstraint(fields=['code', 'owner'], name='code_unique_per_user') ] """core/forms.py""" from django import forms from core.models import Note class NoteForm(forms.ModelForm): class Meta: model = Note fields = ( 'code', ... ) """core/views.py""" from core.models import Note from core.forms import NoteForm def create_note(request): note = Note(owner=request.user) if request.method == "POST": form = NoteForm(request.POST, instance=note) if form.is_valid(): form.save() return redirect(reverse('core:manage_notes')) else: form = NoteForm(instance=note) args = {'form': form} return render(request, 'core/create_note.html', args) Now when creating a Note using NoteForm, the UniqueConstraint is not checked during validation, because the form does not include the onwer field. What would be the best way to make this UniqueConstraint validation happen ? Including the owner field and setting it as hidden works, but doesn't feel right, because … -
Why is pytest not running my tests and skipping them
I am using pytest-django to test my django application. My directory structure is like this : . ├── Dockerfile ├── Pipfile ├── Pipfile.lock ├── README.md ├── app │ ├── __pycache__ │ │ └── test_example.cpython-37-pytest-5.2.1.pyc │ ├── app │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-37.pyc │ │ │ ├── settings.cpython-37.pyc │ │ │ └── urls.cpython-37.pyc │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── core │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-37.pyc │ │ │ ├── admin.cpython-37.pyc │ │ │ └── models.cpython-37.pyc │ │ ├── admin.py │ │ ├── apps.py │ │ ├── migrations │ │ │ ├── 0001_initial.py │ │ │ ├── __init__.py │ │ │ └── __pycache__ │ │ │ ├── 0001_initial.cpython-37.pyc │ │ │ └── __init__.cpython-37.pyc │ │ ├── models.py │ │ └── tests │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-37.pyc │ │ │ ├── test_admin.cpython-37-pytest-5.2.1.pyc │ │ │ └── test_models.cpython-37-pytest-5.2.1.pyc │ │ ├── test_admin.py │ │ └── test_models.py │ ├── db.sqlite3 │ ├── manage.py │ ├── pytest.ini │ └── test_example.py └── docker-compose.yml The file : test_models.py is like below : from django.contrib.auth import get_user_model … -
Have an idea but I am not sure how to go about it and if django alone would be enough?
I technically have 2 questions that I am combining into 1 post. In views we can run python stuff just as usual right? So how demanding a thing can I put in a view. Say I had some game made using pygame and PyOpenGL(3D). Can I put that in a view and expect it to work or do I need to do something additional to it because it is going to end up on a website and I need to know much I can stress django. The other part of the question is that, would it be dependent on the server django is being hosted on. Can I make it client sided (or is it so by default, knowing how powerful django is, I would expect it to be so). I know some part of this question is quite a bit 'noobish' but I am technically noob when it comes to django. All I have done is build one website with some forms and stuff (Basic beginner stuff). But now I am interested in stepping things up! The other thing is most of my projects and games that I run is on git hub and I have recently considered to … -
how to check if the variable has a same value and return it as one value in python
I have four variables with in a defined function. def xyz(): a_1 = self.bal.getcod1() a_2 = self.bal.getcod2() a_3 = self.bal.getcod3() a_4 = self.bal.getcod4() i = getx(a_1) j = getx(a_2) k = getx(a_3) l = getx(a_4) val = i*j*k*l return val For eg : Based on the return value of getcod() i get 2,3,2,3 as a_1,a_2,a_3,a_4 respectively. I dont want duplicates to pass into the four variables i,j,k,l I want 2,3 to pass only once in two variables out of four variables and the rest should do nothing. If i have all 4,4,4,4 then only one time i need to pass it to one variable out of four variables and the rest should do nothing. If i have all 1,1,1,4 then i need 1,4 alone to pass it to two variables out of four variables and the rest should do nothing. so that i can avoid to return duplicate multiplied data in 'Val' variable. -
Failed to execute refresh metadata course in discovery service
I'm trying to install openedx in production environment: https://openedx.atlassian.net/wiki/spaces/OpenOPS/pages/146440579/Native+Open+edX+Ubuntu+16.04+64+bit+Installation Then I wanted to run the refresh refresh_course_metadata in discovery service with a production environment. I created an Oauth2 client in lms. I created a partner in discovery admin interface and I set the lms url and the client_id and the client sercret. When I executed the refresh course metadata command in discovery service I got the following error Traceback (most recent call last): File “/edx/app/discovery/discovery/course_discovery/apps/course_metadata/management/commands/refresh_course_metadata.py”, line 31, in execute_loader loader_class(*loader_args, loader_kwargs).ingest() File “/edx/app/discovery/discovery/course_discovery/apps/course_metadata/data_loaders/api.py”, line 82, in ingest response = self._make_request(initial_page) File “/edx/app/discovery/discovery/course_discovery/apps/course_metadata/data_loaders/api.py”, line 120, in _make_request return self.api_client.courses().get(page=page, page_size=self.PAGE_SIZE, username=self.username) File “/edx/app/discovery/venvs/discovery/lib/python3.5/site-packages/slumber/init.py”, line 155, in get resp = self._request(“GET”, params=kwargs) File “/edx/app/discovery/venvs/discovery/lib/python3.5/site-packages/slumber/init.py”, line 103, in _request raise exceptions.HttpServerError(“Server Error %s: %s” % (resp.status_code, url), response=resp, content=resp.content) slumber.exceptions.HttpServerError: Server Error 500: http://*********/api/courses/v1/courses/ In the lms logs I found: Traceback (most recent call last): File “/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/handlers/exception.py”, line 41, in inner response = get_response(request) File “/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/handlers/base.py”, line 249, in _legacy_get_response response = self._get_response(request) File “/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/handlers/base.py”, line 187, in _get_response response = self.process_exception_by_middleware(e, request) File “/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/handlers/base.py”, line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File “/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/utils/decorators.py”, line 185, in inner return func(*args, **kwargs) File “/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/views/decorators/csrf.py”, line 58, in wrapped_view return view_func(*args, **kwargs) File … -
Class generic DeleteView not working for model related to model
I have a page containing assignment questions. Questions related to assignment is displayed on asisgnment details page with EDIT and DELETE anchor tags. But after pressing delete I get an error : Reverse for 'CreateQuestion' with arguments '('',)' not found. 1 pattern(s) tried: ['assignment/(?P[0-9]+)/createQuestion/$'] views.py class AssignmentDetailView(generic.DetailView): model = Assignment template_name = "dashboard/assignment_detail.html" class QuestionDeleteView(DeleteView): model = Question template_name = 'dashboard/assignment_detail.html' def get_success_url(self): return reverse_lazy('assignment_detail', kwargs={'pk': self.object.assignment_id}) urls.py path('<int:assignment_pk>/DeleteQuestion/<int:pk>/delete', views.QuestionDeleteView.as_view(), name='DeleteQuestion'), path('<int:pk>/createQuestion/', views.QuestionCreate, name='CreateQuestion'), path('assignment/<int:pk>', views.AssignmentDetailView.as_view(), name='assignment_detail'), assignment_detail.html <td> <a onclick="return confirm('Are you sure?');" href="{% url 'DeleteQuestion' assignment_pk=assignment.id pk=question.id %}">Delete</a></td> Models.py class Assignment(models.Model): number = models.IntegerField() course = models.ForeignKey(Course,on_delete = models.SET_NULL,blank=True,null=True) publish_date = models.DateField(auto_now_add = True) deadline_date = models.DateField() faculty = models.ForeignKey(Faculty,on_delete = models.SET_NULL,blank=True,null=True) def __str__(self): return f'Assignment {self.number}-{self.course}' def get_absolute_url(self): """Returns the url to access a detail record for this Assignment.""" return reverse('assignment-detail', args=[str(self.id)]) class Question(models.Model): assignment = models.ForeignKey(Assignment, on_delete=models.SET_NULL,blank=True,null=True) username = models.ForeignKey(User,on_delete=models.SET_NULL,blank=True,null=True) title = models.CharField(max_length = 200) description = models.TextField(blank=True , null = True) marks = models.IntegerField(null=True) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title def get_absolute_url(self): """Returns the url to access a detail record for this book.""" return reverse('question-detail', args=[str(self.id)]) -
Django views.py initalisation per session for external Databases
In Django I would like to access an external ArangoDB and do, after the initialisation some calculation with the data. This data-object should be kept alive during a session and will be accessed in several function calls of the views.py. I'm new to Django but I used to work with Java and Apache Tomcat, so I hope there are some parallels. From what I see there is no initialization or Session-Object in the views.py. Also I haven't really done much with the wsgi dev server and I'm not sure if it's the responsibility of the wsgi to do that (or how?) What would be a proper approach to initialize some objects per session within the views.py and what is necessary to keep them alive? -
when i converting second in minutes in django wy i getting error?
i try to convert second to minute but i am getting error def convert(seconds): seconds = seconds % (24 * 3600) hour = seconds // 3600 seconds %= 3600 minutes = seconds // 60 seconds %= 60 return "%dh:%02dm" % (hour, minutes ) Here i try to convert second to hour and minute def get_total_movingtime(self, obj): totalpieces = WorkDay.objects.filter().aggregate( total_movingtime=Round(Sum(convert('foot_time')))) return totalpieces["total_movingtime"] Error is "not all arguments converted during string formatting" How to resolve this Thanks