Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
changing django model filed data before saving to database
i want to update model field data before saving to database. class mynumber(TimeStampedModel): text = models.TextField(max_length=10000, null=True, blank=True) number = models.DecimalField(default=0, max_digits=9, decimal_places=2) #serializer file class mynumberSerializer(serializers.ModelSerializer): class Meta: model = mynumber fields = "__all__" #view class MyquantityViewSet(CreateListMixin, mixins.CreateModelMixin, viewsets.GenericViewSet): serializer_class = mynumberSerializer queryset = mynumber.objects.all() i want to divide number field before saving to database. what should be the best aproach? -
Can't call objects from class in loop Python Django
I an newbee to Django and I realise that it is a very silly question but, when I put objects in a HTML code to call index from data base I recieve just text of what I am calling: List of news(item.title)(item.title)(item.title)(item.title) views.py: from django.shortcuts import render from django.http import HttpResponse from .models import News def index(request): news = News.objects.all() res = '<hi>List of news</h1>' for item in news: res += f'<div><p>(item.title)</p></div>' return HttpResponse(res) -
GenericRelation inherited from Abstract model in other app failing to generate migration
So I'm trying to create a new model in a new app B, inheriting from an abstract model in app A: # app_b/models.py from app_a.models import Foo class ConcreteModel(Foo): pass Foo has a GenericRelation to another model of app A: # app_a/models.py from django.contrib.contenttypes.fields import GenericRelation class Foo(models.Model): class Meta: abstract = True some_relation = GenericRelation( "Bar", content_type_field="foo_type", object_id_field="foo_id" ) class Bar(models.Model): # whatever Generation of the initial migration of app B fails with the following SystemCheck errors: <function GenericRelation.contribute_to_class..make_generic_foreign_order_accessors at 0x7fa2a6747c80>: (models.E022) <function GenericRelation.contribute_to_class..make_generic_foreign_order_accessors at 0x7fa2a6747c80> contains a lazy reference to app_b.bar, but app 'app_b' doesn't provide model 'bar'. app_b.ConcreteModel.some_relation: (fields.E307) The field app_b.ConcreteModel.some_relation was declared with a lazy reference to 'app_b.bar', but app 'app_b' doesn't provide model 'bar'. Indeed, app_b does not provide Bar, app_a does. I tried explicitly mentioning app_a in the GenericRelation: some_relation = GenericRelation( "app_a.Bar", content_type_field="foo_type", object_id_field="foo_id" ) but this does not generate a migration for app_a, nor does it fix the problem. I'm using Django 2.2. Is there a workaround besides moving ConcreteModel to app_a ? -
How can i deal with aws django-storages storages error
when i run django on elastic beanstalk, I used this requirements.txt #requirements.txt asgiref==3.3.4 boto3==1.17.94 botocore==1.20.94 Django==3.2.4 django-storages==1.11.1 jmespath==0.10.0 python-dateutil==2.8.1 pytz==2021.1 s3transfer==0.4.2 six==1.16.0 sqlparse==0.4.1 urllib3==1.26.5 #settings.py DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage' to upload media files to s3 But at the same time i got this error /var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/storages/__init__.py:9: UserWarning: This library has been designated as the official successor of django-storages and releases under that namespace. Please update your requirements files to point to django-storages. I did reinstall django-storages and any other thing which is on google but it didn't work How can i deal with this error? -
django.db.utils.OperationalError: 3780 Referencing column and referenced column are incompatible
I'm trying to add a foreign key relation between two models in Django, but I'm getting this error. Notification model: class Notification(models.Model): ... lab_extension = models.ForeignKey(Labs, on_delete=models.CASCADE, null=True, to_field='lab_id') Lab model class Lab(models.Model): lab_id = models.AutoField(primary_key=True) lab_name = models.CharField(max_length=40) lab_model = models.IntegerField() After assigning this foreign key field to the Notification model, I get this error when doing python manage.py migrate: django.db.utils.OperationalError: (3780, "Referencing column 'lab_extension_id' and referenced column 'lab_id' in foreign key constraint [constraint name] are incompatible.") It's likely this error will not persist if I remove AutoField from the Lab model, and use the default id field. But I'm at a point into the project where I can't do that. I also realize a foreign key field is generally not nullable, but for this project, the Notification model may or may not point to a Lab model. -
Why is adding styling or widgets to Django forms will prevent data from being saved in database?
I just tried multiple ways of styling my Django form but every time I did it prevents data from being saved in Django's admin database. Here is my code : models.py : class listing(models.Model): title = models.CharField(max_length=64) describtion = models.CharField(max_length=300) bid = models.FloatField() category = models.ForeignKey(categories, default=1, verbose_name="Category", on_delete=models.SET_DEFAULT) user = models.ForeignKey(User,default='', verbose_name="User", on_delete=models.SET_DEFAULT) image = models.CharField(max_length=400) def __str__(self): return f"{self.title} " class create(ModelForm): class Meta: model = listing fields = [ 'title', 'describtion','bid','category','image'] After adding widgets : class create(ModelForm): class Meta: model = listing fields = [ 'title', 'describtion','bid','category','image'] widgets={ 'title': TextInput(attrs={'class':'form-control'}), 'describtion': TextInput(attrs={'class':'form-control'}), 'image': TextInput(attrs={'class':'form-control'}), 'bid': NumberInput(attrs={'class':'form-control'}), 'category': SelectMultiple(attrs={'class':'form-control'}), } Views.py: def CreateListing(request): user = request.user if request.method == "POST": form = create(request.POST, request.FILES) if form.is_valid(): form.instance.user = user form.save() return redirect('listing') else: return render(request, "auctions/Create.html",{ 'form': create }) Ps : without widgets, data will be saved in the Database. -
Update field with Django ORM based on computed value
I have a basic model: class MyModel(Model): id = models.IntegerField() is_admin = models.BooleanField() What I want to achieve is to update the value of the is_admin field for the entire table at once, based on whether or not the id value is in a certain list of values. Basically, in raw SQL, this is the query I want: UPDATE my_model SET is_admin = (id IN (1, 2, 3, 4)) How can I achieve this with Django's ORM? This is what I tried so far: from django.db.models import F, Value admin_ids = (1, 2, 3, 4) MyModel.objects.update(is_admin=F("id") in admin_ids) # Resulting query is: # UPDATE my_model SET is_admin = false MyModel.objects.update(is_admin=F("id") in Value(admin_ids)) # TypeError: argument of type 'Value' is not iterable MyModel.objects.filter(id__in=admin_ids).update(admin=True) MyModel.objects.exclude(id__in=admin_ids).update(admin=False) # it works... but can I do this in a single query instead of two? I'm using Django 3.2 and PostgreSQL. -
Search model field with TrigramSimilarity
i have a model named cars, the method search_text() is a str containing the values of model and modelcatregory. Then i have my searchview but i cant use search on the method search_text(). I get a error Unsupported lookup 'profession.search_text()' for AutoField or join on the field not permitted. is it possible to make a searcheable model field by joining to other fields? And how can i cal that function in my search? Model: class Cars(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) active = models.BooleanField(_('active'), default=True) model = models.ForeignKey(Model, on_delete=models.SET_NULL, null=True) modelcategory = models.ForeignKey(Modelcategory , on_delete=models.SET_NULL, null=True) posted_on = models.DateTimeField(_('registrerad'), auto_now_add=True) updated_on = models.DateTimeField(_('last updated'), auto_now=True) years_of_exp = models.CharField(_('years of experiance'), max_length=20, choices=YEARS_OF_EXP, null=True, blank=True) def search_text(self): searchtext = str(self.model) + ' - ' + str(self.modelcategory) return searchtext Search view def cars_search(request): form = SearchForm() query = None results = [] if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): query = form.cleaned_data['query'] results = User.objects.filter(is_active=True).exclude(Q(cars__isnull=True) | Q(id=request.user.id)) results = results.annotate( similarity=TrigramSimilarity('cars__search_text', query), ).filter(similarity__gt=0.3).order_by('-similarity') return render(request, 'users/search.html', {'form': form, 'query': query, 'results': results}) -
Combining View and Viewset Django
I have a serializer for StacItem and a simple viewset for it say class StacItemSerializer(serializers.ModelSerializer): type = serializers.SerializerMethodField() id = serializers.SerializerMethodField() ... class StacItemViewSet(viewsets.ModelViewSet): serializer_class = StacItemSerializer queryset = StacItems.objects.all() I also created a custom view class StacItemMainView(APIView): def get(self, request): items = {} items['type'] = "Example" return Response(items) In my urls urlpatterns = [ url(r'items', StacItemMainView.as_view()), ] router.register(r'items/<id>', StacItemViewSet, basename='item') urlpatterns += router.urls What I want to achieve is to have an endpoint to apps/items/ using the APIView and on the same time I want the endpoint for each Item i.e. apps/items/{id} from the viewset using the serializer. How can I customize the urls to point it correctly? -
Django filtering doesn't work with checkboxes
As far as i've understood my view doesn't get checked checkboxes. I can create 5 variables for 5 checkboxes but it seems to me wrong. I need to get all checked colors in variable 'color' and materials in 'material'. Then need to get all objects from database that satisfying these checked checkboxes My form: <form action="{% url 'filter' %}" method="POST">{% csrf_token %} <h2>Color:</h2> <input type="checkbox" name="red" id="" value="Red">Red<br> <input type="checkbox" name="blue" id="" value="Blue">Blue<br> <h2>Material:</h2> <input type="checkbox" name="wood" id="" value="Wood">Wood<br> <input type="checkbox" name="plastic" id="" value="Plastic">Plastic<br> <input type="checkbox" name="metal" id="" value="Metal">Metal<br> <button type="submit" value="Submit">Find!</button> </form> My django model: class Toy(models.Model): COLORS = ( ('Blue', 'Blue'), ('Red', 'Red') ) MATERIALS = ( ('Plastic', 'Plastic'), ('Wood', 'Wood'), ('Metal', 'Metal') ) photo = models.ImageField(upload_to='images/', blank=True) title = models.CharField(max_length=128, blank=False) description = models.CharField(max_length=5000, blank=False) price = models.PositiveIntegerField(blank=False) count = models.PositiveIntegerField(blank=False) color = models.CharField(max_length=128, blank=False, choices=COLORS) material = models.CharField(max_length=128, blank=False, choices=MATERIALS) My views.py def filter(request): products = Toy.objects.all() material = request.POST.get("what do i need to add here to find all products that satisfiying checked material checkboxes?") color = request.POST.get("the same but with color") if material: products = products.filter(material__in=material) if color: products = products.filter(color__in=color) return render(request, 'catalog/products.html', {'products': products}) -
Django NoReverseMatch and Django-Verify-Email
I hope someone can help me with this bug. So, I am using Django-Verify-Email as a library to send verifications emails from my app, and, according to the wiki, they use the LOGIN_URL variable in the settings of the app. The problem is that, at the moment, I want to change this LOGIN_URL to the homepage ('index'or '/' or 'mainpage') but it throws me a error (Django 3.2). Any help is apreciatted! Reverse for 'index' not found. 'index 'is not a valid view function or pattern name. Index is at the core of the project, and not inside any app. urls.py: from django.urls import path, include import user.urls from .views import index import calculator.urls urlpatterns = [ path('admin/', admin.site.urls), path('', index, name='mainpage'), ] views.py: from django.shortcuts import render def index(request): return render(request, 'index.html') -
Django Channels websocket unexpectedly disconnects with 1011 error
I'm writing an app which requires a socket connection, and I'm having problems with websockets being disconnected after ~4/5 seconds, with my front getting an 1011 error code. My consumer gets connected, I can send messages to it, and it will send them back to me correctly before disconnecting unexpectedly. My consumer file looks like this : class GameConsumer(WebsocketConsumer): def connect(self): print("[info] new client connected") self.accept() def receive(self, text_data=None, bytes_data=None): print("[info] receiving message") self.send(text_data="ALLO") print("[info] message sent back") def disconnect(self, event): print("[info] client disconnected") My settings: ASGI_APPLICATION = 'restAPI.asgi.application' CHANNEL_LAYERS = { "default": { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [("redis", 6379)], } }, } And my asgi application: import os from channels.routing import get_default_application from channels.routing import ProtocolTypeRouter from api.routing import websockets os.environ.setdefault("DJANGO_SETTINGS_MODULE", "restAPI.settings") application = ProtocolTypeRouter({ "websocket": URLRouter([ path( "ws/game/<str:uuid>", GameConsumer.as_asgi(), name="game", ), ]), }) I can write debug strings when websockets are connected from both sides, when messages are sent and read, and when I disconnect by myself, without waiting for the error to trigger. But if I wait more than 5 seconds before closing it the connection will shutdown with the 1011 error code. Can anyone tell me what can be failing in this ? I'm using … -
Django - 404 Error for static files after Cache Busting
Django version 3.2.3 I am trying to implement cache busting in Django. # settings.py DEBUG = False STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' STATIC_ROOT = 'assets' STATIC_URL = '/assets/' # Collecting all static files from this Dir STATICFILES_DIRS = [ BASE_DIR / 'static',] python manage.py collectstatic successfully generated the static files with hash in my assets folder. Example: style.7b0b119eddb7.css Now, after running the server all static files end up with a Error-404 Later, I ran it with Debug = False and obviously all static files loaded correctly but they weren't the hashed files. GET /assets/css/bootstrap.min.css HTTP/1.1 200 GET /assets/css/bootstrap.min.2618ae4d1f4a.css HTTP/1.1 404 -
How can I load a cropped image with previously obtained data?
I'm using jcrop to obtain some user input on where they want to crop an Image, but instead of saving the cropped image, I'm trying to save only information about the area cropped so I can render it later in other pages, I was wondering if it's possible, so far I've tried to apply css with javascript but so far without success -
|as_crispy_field got passed an invalid or inexistent field while passing context from my django form
Help!!! I'm lost on this erro: while trying to submit this form and pass it content as a context: I see that the identition of my view is correct as well as the definitions of my form View def costm_questions(request): if request.method == 'POST': form = labor_questions(request.POST) if form.is_valid(): cost_dict= dict() cost_dict['Union_PWR']= form.cleaned_data['Union_PWR'] cost_dict['UnionLabor_area']= form.cleaned_data['UnionLabor_area'] cost_dict['After_Hours_Req']= form.cleaned_data['After_Hours_Req'] cost_dict['infectious_control_Req']=form.cleaned_data['infectious_control_Req'] cost_dict['No_Core_Drills']= form.cleaned_data['No_Core_Drills'] cost_dict['Armored_fiber_req']= form.cleaned_data['Armored_fiber_req'] cost_dict['cost_dict']= cost_dict context = { 'cost_dict': cost_dict, } return render(request, 'building_form.html', context) else: form = labor_questions()`enter code here` return render(request, 'cost_questions_form.html', {'form': form}) Forms class labor_questions(forms.Form): BOOL_CHOICES = ((True, 'Yes'), (False, 'No')) LABOR_AREA_CHOICES= ((1, '1) Chicago'), (2 ,'2) Manhattan'), (3 ,'3) NYC Metro'), (4 ,'4) Los Angeles'), (4 ,'5) San Francisco'), (5 ,'6) Philadelphia'), (5 ,'6) Other')) AFTER_HOURS_CHOICES= ((1, '1) No'), (2, '2) Yes, Mon-Fri'), (3,'3) Yes, weekends only')) Union_PWR = forms.ChoiceField(choices = BOOL_CHOICES, label="Is Union Labor or Prevailing Wage Required?", initial='', widget=forms.Select(), required=True) #Is Union Labor or Prevailing Wage Required? UnionLabor_area= forms.ChoiceField(choices = LABOR_AREA_CHOICES, label="if yes please choose union area", initial='', widget=forms.Select(), required=True) After_Hours_Req= forms.ChoiceField(choices = AFTER_HOURS_CHOICES, label="Is after-hours work required?", initial='', widget=forms.Select(), required=True) infectious_control_Req= forms.ChoiceField(choices = BOOL_CHOICES, label="Is tenting required for infectious control?", initial='', widget=forms.Select(), required=True) No_Core_Drills = forms.IntegerField(label='How many core drills will be required?', required=True) … -
problem in otp validation during login in django rest
I am trying to send otp and then validate otp for login. I am able to send otp but it is not validating for some reason. the code for sending otp is below and it is working fine- class SendOTP(APIView): permission_classes = (AllowAny, ) def post(self, request, *args, **kwargs): email = request.data.get('email') if email: email = str(email) user = User.objects.filter(email__iexact = email) if user.exists(): key = send_otp(email) if key: old = User.objects.filter(email__iexact=email) if old.exists(): old = old.first() count = old.count old.count = count + 1 old.save() print('Count Increase', count) return Response({ 'status': True, 'detail': 'OTP sent successfully.' }) code for generating 6 digit otp is - def send_otp(email): if email: digits = [i for i in range(0, 10)] key = "" for i in range(6): index = math.floor(random.random() * 10) key += str(digits[index]) print(key) return key else: return False code for validating email and otp is below but it is not working- class ValidateOTP(APIView): permission_classes = (AllowAny, ) def post(self, request, *args, **kwargs): email = request.data.get('email' , False) otp_sent = request.data.get('otp', False) if email and otp_sent: e_mail = User.objects.filter(email__iexact = email) if old.exists(): e_mail = e_mail.first() otp = e_mail.otp print(otp, e_mail, otp_sent) if str(otp_sent) == str(otp): old.validated = True old.save() … -
I want to send list from javascript to django views.py
in this i want to send variable list[] to django. And i have tried many methods but i didnt get how to pass this list to django plz help me to get rid of this. Thanku in Advance. function add_item(item,next){ list.push(item.name); item.parentNode.style.display = "none"; next.style.display = "block"; console.log(list); } function remove_item(item,prev){ for (var i = 0; i <= list.length; i++) { if (list[i]===item.name) { list.splice(i,1); } } item.parentNode.style.display = "none"; prev.style.display = "block"; } $(document).ready(function() { $.ajax({ method: 'POST', url: '/food_output', data: {'list': list}, success: function (data) { //this gets called when server returns an OK response alert("it worked!"); }, error: function (data) { alert("it didnt work"); } }); });``` -
Field 'id' expected a number but got ''
I am trying to display all the posts by a particular user in their profile page.. So if someone visits my profile page, they can see all of my posts and so on. all_post_by_user = Log.objects.filter(author=username) I am getting the post by a particular username.. author is defined in models.py username is passed as an argument to the view.. I am getting the error The below is my profile.html: {% extends 'log/base.html' %} {% block content %} {% load socialaccount %} {% get_social_accounts profile as accounts %} {%load crispy_forms_tags %} <title>Error logger - Profile {{ profile.username }}</title> <div class="content-section card bg-dark text-white p-4"> <div class="media"> {% if profile.username == user.username %} {% if accounts %} <img class='rounded-circle account-img' src="{{ profile.socialaccount_set.all.0.get_avatar_url }}" /> {% else %} <img class="rounded-circle account-img" src="{{ profile.profile.avatar.url }}"> {% endif %} {% else %} {% if accounts %} <img class='rounded-circle account-img' src="{{ profile.socialaccount_set.all.0.get_avatar_url }}" /> {% else %} <img class="rounded-circle account-img" src="{{ profile.profile.avatar.url }}"> {% endif %} {% endif %} <div class="media-body"> <h2 class="account-heading">{{profile.username}}</h2> <p >{{profile.email}}</p> <p>Created on: {{ profile.profile.created }}</p> {% if profile.username == user.username %} <p>Last updated on : {{ profile.profile.updated }}</p> {% endif %} </div> </div> <!-- FORM HERE --> {% if profile.username == … -
Django Foreign Key Relation Fails: Referencing column and referenced column in foreign key constraint are incompatible
I'm trying to add a foreign key relation between two models in Django, but I'm getting this error. Here is the Lab model: class Lab(models.Model): lab_id = models.AutoField(primary_key=True) lab_name = models.CharField(max_length=40) lab_model = models.IntegerField() And here is the Notification model that needs to have a foreign key field relation with the Lab model: class Notification(models.Model): ... lab_extension = models.ForeignKey(NokiaLabs, on_delete=models.CASCADE, null=True, to_field='lab_id') After assigning this foreign key field to the Notification model, I get this error when doing python manage.py migrate: django.db.utils.OperationalError: (3780, "Referencing column 'lab_extension_id' and referenced column 'lab_id' in foreign key constraint [fk constraint name] are incompatible.") It's likely this error will not persist if I remove the AutoField from the Lab model, and use the default id field. But I'm at a point into the project where I can't do that. I also realize a foreign key field is generally not nullable, but for this project, the Notification model may or may not point to a Lab model. -
Group by in Django with field distinction
I have two tables, one for products and one for suppliers, I did a query that returns this: select f.nome, f.cnpj, sum(p.quantidade) as "Quantidade de Produtos", count(distinct categoria_id) as "Categorias com Produtos " from core_produtos p inner join core_fornecedor f on p.fornecedor_id=f.id group by f.nome, f.cnpj order by f.nome ASC; and she returns a table like this: nome | cnpj | Quantidade de Produtos | Categorias com Produtos --------------+--------------------+------------------------+-------------------------- fornecedor 1 | 10.331.608/0001-52 | 7339 | 5 fornecedor 2 | 00.333.725/0001-00 | 7673 | 5 fornecedor 3 | 88.550.421/0001-37 | 8423 | 5 fornecedor 4 | 03.251.500/0001-94 | 14101 | 5 fornecedor 5 | 25.862.630/0001-04 | 8988 | 5 my question is: how do I query using django's ORM? -
Automatic ldap login is possible using django-auth-ldap package?
how to achieve automatic ldap login in django application? is it possible by using django-auth-ldap package? -
is there any way to use the path argument in extra_context dict in django?
I have an url into my url patterns like this: path("object_edit/<id>/",TemplateView.as_view("object_edit.html") There is any way to use de argument in the pattern to pass it as extra_context to the template? -
How can i add diffrent sizes of the same product?
I have created a function where i can add products to my shopping cart. The problem is that when i add one product at a time, from different product that is, it works. But when i try to add the same product in different sizes i get this error, how do i fix this?. def add_cart_size(request, product_id, product_size): product = Product.objects.get(id=product_id) product_size = ProductSize.objects.get(pk=product_size) print('size', product_size) try: cart = Cart.objects.get(cart_id=_cart_id(request)) except Cart.DoesNotExist: cart = Cart.objects.create( cart_id=_cart_id(request) ) cart.save() try: cart_item = CartItem.objects.get(product=product, cart=cart, size=product_size.name) # noqa:501 if cart_item.quantity < cart_item.product.stock: cart_item.quantity += 1 cart_item.save() except CartItem.DoesNotExist: cart_item = CartItem.objects.create( product=product, quantity=1, cart=cart, size=product_size.name ) cart_item.save() return redirect('cart_detail') def add_cart(request, product_id): product = Product.objects.get(id=product_id) try: cart = Cart.objects.get(cart_id=_cart_id(request)) except Cart.DoesNotExist: cart = Cart.objects.create( cart_id=_cart_id(request) ) cart.save() try: cart_item = CartItem.objects.get(product=product, cart=cart) if cart_item.quantity < cart_item.product.stock: cart_item.quantity += 1 cart_item.save() except CartItem.DoesNotExist: cart_item = CartItem.objects.create( product=product, quantity=1, cart=cart ) cart_item.save() return redirect('cart_detail') def cart_detail(request, total=0, counter=0, cart_items=None): try: cart = Cart.objects.get(cart_id=_cart_id(request)) cart_items = CartItem.objects.filter(cart=cart, active=True) for cart_item in cart_items: total += (cart_item.product.price * cart_item.quantity) counter += cart_item.quantity except ObjectDoesNotExist: pass return render(request, 'cart/cart.html', dict(cart_items=cart_items, total=total, counter=counter)) # noqa:501 def cart_remove(request, product_id): cart = Cart.objects.get(cart_id=_cart_id(request)) product = get_object_or_404(Product, id=product_id) cart_item = CartItem.objects.get(product=product, cart=cart) … -
How to remove microseconds in django DateTimeField
Hi people I have a datetimefield in my projects Model the original value is the below: 2021-06-15 21:39:06.842317 after using datetime.now().strftime("%Y-%m-%d %H:%M:%S") this is the result: 2021-06-15 21:39:06.000000 the thing is after using the formatted code the result is this: 2021-06-15 21:39:06 but after inserting it, it added .000000 in the end. Does it have to do with DateTimeField itself? I just rerun it just now and I see this warning: RuntimeWarning: DateTimeField AttendanceTbl. start_date received a naive datetime (2021-06-15 21:47:55) while time zone support is active. warnings.warn("DateTimeField %s received a naive datetime (%s)" -
Looping over a queryset based on queryset
I am trying to get data from queryset(Answers) based on values from a queryset(Modules) and adding them finally into a list and sending to front to plot on different graphs. Models.py class Answers(models.Model): _id = models.AutoField(primary_key=True) question = models.ForeignKey(Questions, db_column="question", on_delete=models.SET_NULL, null=True) # points= models.IntegerField(null=True, blank=True) points = models.CharField(max_length = 100 ,choices= asssess_choice, null=True) student = models.ForeignKey(Students, on_delete= DO_NOTHING,) def __str__(self): return str(self.question) class Modules(models.Model): md_id = models.AutoField(primary_key=True) mod_name = models.CharField(max_length=100) # student = models.ForeignKey(Students, on_delete= DO_NOTHING) # percentage = models.FloatField(default="0.00") def __str__(self): return self.mod_name views.py def studentView(request, studentid=None): context = {} cant_assess = 0 yes = 0 no = 0 somewhat_assess = 0 module_query = Modules.objects.values() # print(module_query) # Running a loop based on query and running next query # for module in module_query: # # print (module['md_id']) query = Answers.objects.values().filter(student = studentid) query2 = query.filter(question__modules = [item['md_id'] for item in module_query]) print(query2) for i in query: if i['points'] == 'No': no = no + 1 if i['points'] == 'somewhat': somewhat_assess = somewhat_assess + 1 if i['points'] == 'cannot': cant_assess = cant_assess + 1 if i['points'] == 'Yes': yes = yes + 1 label = [] data = [] data.append(yes) data.append(no) data.append(somewhat_assess) data.append(cant_assess) label.append('Yes') label.append('No') label.append('Somewhat Assess') label.append('cant Assess') …