Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
No module named 'sklearn' while running django server
I saved a model using joblib and was trying to run server using but it shows no module as sklearn even though it is downloaded in the environment, can anyone please help? -
Cannot render model fields in forloop (Django)
I am using .values() and .annotate()to sum up 2 models fields based on matching criteria. I wrapped this in a forloop in my template to iterate. Problem: I cannot call the model fields anymore. The forloop returns the venue_id instead of the name and the usual approach to call the logo does not work anymore. (these were rendering fine before I used .values() and .annotate(). Makes me think I am missing something in the logic here. Any ideas? Models class Venue(models.Model, HitCountMixin): id = models.AutoField(primary_key=True) name = models.CharField(verbose_name="Name",max_length=100, blank=True) logo = models.URLField('Logo', null=True, blank=True) class Itemised_Loyatly_Card(models.Model): user = models.ForeignKey(UserProfile, blank=True, null=True, on_delete=models.CASCADE) venue = models.ForeignKey(Venue, blank=True, null=True, on_delete=models.CASCADE) add_points = models.IntegerField(name = 'add_points', null = True, blank=True, default=0) use_points = models.IntegerField(name= 'use_points', null = True, blank=True, default=0) Views from django.db.models import Sum, F def user_loyalty_card(request): itemised_loyalty_cards = Itemised_Loyatly_Card.objects.filter(user=request.user.id).values('venue').annotate(add_points=Sum('add_points')).annotate(use_points=Sum('use_points')).annotate(total=F('add_points')-F('use_points')) return render(request,"main/account/user_loyalty_card.html", {'itemised_loyalty_cards':itemised_loyalty_cards}) Templates {%for itemised_loyatly_card in itemised_loyalty_cards %} <img"src="{{itemised_loyatly_card.venue.logo}}"> {{itemised_loyatly_card.venue}} {{itemised_loyatly_card.total}} {%endfor%} Renders -
Get objects where (val1, val2) both in (other_val1, other_val2, ...)
Given the models below class Language(models.Model): name = models.CharField(max_length=255, unique=True) class Profile(models.Model): languages = models.ManyToManyField(Language) class Job(models.Model): language1 = models.ForeignKey( Language, models.CASCADE, related_name='language1' ) language2 = models.ForeignKey( Language, models.CASCADE, related_name='language2' ) If a profile has n languages, usually 2 or more, I need to get the jobs matching these languages in a way that both language1 and language2 are present in the language-user table. The models above generate app_profile, app_job, app_language and app_profile_languages. Below is the query I need to convert to orm: with user_languages as (select language_id from app_profile_languages where profile_id = 6) select * from app_job where language1_id in (select * from user_languages) and language2_id in (select * from user_languages) Here's a sample input and output app_language id name 1 English 2 German 3 Russian 4 Chinese app_job id language1_id language2_id 1 1 4 2 3 2 3 2 3 app_profile_languages id profile_id language_id 1 1 2 2 1 3 3 2 2 4 2 4 If profile_id = 1 is selected, this would be the expected output id language1_id language2_id 2 3 2 3 2 3 -
How do I display all the children of a parent in Django Rest Framework?
I have this model that is a reply to a post. But replies can also have replies and it can carry on forever. If I look at a reply I would like to see all its children and other information related to that specific reply like the user profile. Here is the reply model class Reply(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) video = models.FileField( upload_to=reply_videos_directory_path, null=True, blank=True ) body = models.TextField(max_length=256, default=None) parent = models.ForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True, related_name="replies" ) created_at = models.DateTimeField(auto_now_add=True, verbose_name="Created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="Updated at") class Meta: verbose_name = "post reply" verbose_name_plural = "post replies" db_table = "post_reply" def __str__(self): return self.body[0:30] and here is the serializer for the reply and I can get the information I need for the parent serializer but how do I pull in any children and further related information like the user profile, if there are any children of the reply? class ReplySerializer(serializers.ModelSerializer): images = ReplyImageSerializer(many=True, read_only=True, required=False) post = serializers.SerializerMethodField() profile = serializers.SerializerMethodField() post_images = serializers.SerializerMethodField() class Meta: model = Reply fields = [ "id", "post", "post_images", "video", "images", "body", "parent", "profile", "created_at", "updated_at", ] depth = 1 def get_post(self, obj): post_obj = Post.objects.get(id=obj.post.id) post … -
No Post matches the given query. django blog
everything is ok in the model but when I try to retrieve the object the error "No Post matches the given query." is shown. I don't know what is the problem that shows this error? **Model** class Post(CoreField): .... slug = models.SlugField(max_length=250, unique_for_date='publish') tags = TaggableManager() publish = models.DateTimeField(default=timezone.now) def get_absolute_url(self): return reverse('news:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) **url** path('<int:year>/<int:month>/<int:day>/<slug:post>/', views.post_detail, name='post_detail'), **views** def post_detail(request, year, month, day, post): single_post = get_object_or_404(Post, publish__year=year, publish__month=month, publish__day=day, slug=post ) # List of active comments for this post comments = post.comments.filter(active=True) # Form for users to comment form = CommentForm() return render(request, 'news/post_detail.html', {'post': single_post, 'comments': comments, 'form': form}) when I remove the remove the "int:year/int:month/int:day/" form url it works. but when I pass the "int:year/int:month/int:day/slug:post/" it does't work. What is the proble and where it happens???? -
Django For Loop messing with Javascript ID
I am trying to make a page that shows multiple social media posts on 1 page. Through using a for loop using the Django template tag, I was able to cycle through the posts and they all showed up on the page. However, I have an image slideshow through each post. While the for loop runs, it keeps the same Javascript names for each post. Thus, only the first post is identified and the left and right arrows only work on the first post. I am new to programming and this is my first time. Any help is appreciated. I found a very similar problem here but I am struggling to apply it to my own code. {% for e in social_info %} <div class="testimonial-box" style=" display: block; margin-left: auto; margin-right: auto; width: 530px; height: 655px; margin-top: 60px; box-shadow: 1px 1px 5px; border-radius: 10px; "> <!-- <div style="margin-top: -20px;"> --> <div class="profile-img"> <img src="static/images/profile.png" /> </div> <div> <h3 style="font-weight: bold; float: left; margin-left: 60px; margin-top:-45px; max-width: 50px; text-transform: none; letter-spacing: 1px;"> @{{e.username}} </h3> <h5 style="float: left; margin-left: 65px; margin-top: -20px; color: black;"> {{e.created_at}} </h5> </div> <!-- start of partial --> <script> function Slider() { const carouselSlides = document.querySelectorAll('.slide'); const btnPrev … -
Use django-redis on AWS beanstalk without Elasticache
I wish to create a cache for an app that will be deployed on AWS Elastic Beanstalk (EB for the rest of the question) but cannot find any tutorial that achieves this without using Elasticache. My question is : is it possible to do it? i.e. launch the app with some EB config that will activate django-redis on the server EB will create and use its memory without linking to any external cache? Thanks -
Dynamic annotion in django queryset
I have a Django queryset being created for a graph like the following: obj = Allotment.objects.all().values('dispatch_date').annotate(transaction_no=Count('transaction_no')).\ values('dispatch_date', 'transaction_no') Now I am trying to pass all these values dynamically so I tried this : data = request.data.copy() x_model = data['x_model'] y_model = data['y_model'] obj = Allotment.objects.all().values('{}'.format(x_model)).annotate(transaction_no=Count('{}'.format(y_model))).\ values('{}'.format(x_model), '{}'.format(y_model)) where I just replaced the string values and it gives me the following error: The annotation 'transaction_no' conflicts with a field on the model. How do I dynamically change the field in annotate function ? and apply aggregators such as Sum, Count, etc given that the aggregators are passed through the API as well -
How change a function based view into a class based?
I want to write a category detail view in order to do so i want to change this function based view def CategoryView(request, cats): category_posts = Post.objects.filter(category=cats.replace('-', ' ')) return render(request, 'categories.html', {'cats':cats.replace('-', ' ').title(), 'category_posts':category_posts}) into the class based view. My first question: 1. How to do so?; 2.How also change the url for the view?; path('category/<str:cats>/', CategoryView, name='category'), Here is my models: from django.conf import settings from django.db import models from django.urls import reverse class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return (self.name) def get_absolute_url(self): return reverse("home") class Post(models.Model): title = models.CharField(max_length=255) body = models.TextField() author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) category = models.ManyToManyField(Category, related_name='categories') def __str__(self): return self.title def get_absolute_url(self): return reverse("post_detail", kwargs={"pk": self.pk}) @property def categories(self): return ', '.join([x.name for x in self.category.all()]) class Comment(models.Model): article = models.ForeignKey(Post, null=True, blank=True, on_delete=models.CASCADE) comment = models.CharField(max_length=140) author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,) def __str__(self): return self.comment def get_absolute_url(self): return reverse("post_list") When you write an answer, if you don't mind, can you also write an explanation a step by step. And can you also write how did you figure out the answer. A lost a useful materials would be also helpful. Thank you in advance -
Does anyone else have images reload or dissapear everytime they push to Heroku?
Whenever I push my git push to heroku the images that were previously uploaded on the site disappear. It still shows the file path on my backend database but the images actually just go to placeholder image. Has anyone else had this problem? I just have no idea what is causing the problem. I have whitenoise installed. I had an issue earlier with the "simple upload" that heroku offers that was not working, but I deleted it. I don't know if there are remnants of the code somewhere that is messing up my server? -
Django query after a given character
I am trying to filter data from the postgres database connected to my django app. The data in the database column to be filtered is in this format e.g Name|ABC & facilities:Unit|XY Unit I want to write a django query that matches the search text after the last pipe ("|") symbol. How can this be done to return the data in shortest time possible. I tried writing a query Mymodel.objects.filter(name__iendswith=searchTxt) but it's not returning any result. -
How to link multiple Django models to display a form?
I'm building an application to track the assignment of applications to employees. Each department has a list of applications that are utilized by employees and each application has a list of optional options (access levels as needed). I'm struggling with how to put the form together by stitching all these models together. My goal is to display applications grouped by their department with their associated options and status. Am I overthinking this? Is there a simpler way to achieve what I'm trying to do? Example: Department: department.name +---------------------+-----------------------------+------------------------+ | application.name | <applicationsubtype.name> | <statuslevel.status> | +---------------------+-----------------------------+------------------------+ which translates to: Department: IT Application Options (drop down) Status (drop down) +---------------------+-----------------------------+-------------------------------+ | Active Directory | Standard/Admin | Unassigned/Assigned/Revoked | +---------------------+-----------------------------+-------------------------------+ +---------------------+-----------------------------+-------------------------------+ | Microsoft Office | | Unassigned/Assigned/Revoked | +---------------------+-----------------------------+-------------------------------+ Below are the models I've created. I can input data via Django Admin but I would like to display it on a form as described above. models.py from django.db import models class Employee(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) employee_id = models.PositiveIntegerField() department = models.ForeignKey("Department", on_delete=models.SET_NULL, null=True, blank=True) job_title = models.ForeignKey("JobTitle", on_delete=models.SET_NULL, null=True, blank=True) applications = models.ManyToManyField("Application", through="ApplicationManager") def __str__(self): return f"{self.first_name} {self.last_name}" class Department(models.Model): name = models.CharField(max_length=100) manager = models.ForeignKey("Employee", on_delete=models.SET_NULL, null=True, … -
Request URL: http://localhost:8000/user Request Method: GET Status Code: 401 Unauthorized Remote Address: 127.0.0.1:8000 in django rest & react axios
i am tring to do untimate authantication in django and reactjs typescript and is giveng me error like 401 i have doing in 3wek to solve this can you help me please """"""""""django"""""""" models.py from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class Users(AbstractUser): first_name = models.CharField(max_length=256) last_name = models.CharField(max_length=256) email = models.CharField(max_length=256,unique=True) password = models.CharField(max_length=256) username = None USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class UserToken(models.Model): user_id = models.IntegerField() token = models.CharField(max_length=256) created_at = models.DateTimeField(auto_now_add=True) expired_at = models.DateTimeField(auto_now=True) class Reset(models.Model): email = models.CharField(max_length=255) token = models.CharField(max_length=256) views.py from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import exceptions from .Serializers import UserSerializers from .models import Users, UserToken, Reset from .authentication import create_access_token, create_refresh_token, JWTAuthentication, decode_refresh_token import datetime, random, string from django.core.mail import send_mail class RegisterAPIView(APIView): def post(self, request): data = request.data if data['password'] != data['password_confirm']: raise exceptions.APIException('password do not match!') serializer = UserSerializers(data=data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) class LoginAPIView(APIView): def post(self, request): email = request.data['email'] password = request.data['password'] user = Users.objects.filter(email=email).first() if user is None: raise exceptions.AuthenticationFailed('Invalid credentials ') if not user.check_password(password): raise exceptions.AuthenticationFailed('Invalid credentials') access_token = create_access_token(user.id) refresh_token = create_refresh_token(user.id) UserToken.objects.create( user_id = user.id, token = refresh_token, expired_at = datetime.datetime.utcnow() + datetime.timedelta(days=7) … -
In Django I created two URLs to insert data and retrieve data [closed]
In Django I created two URLs to insert data and retrieve data but As I can check in database data is inserted properly in table but it is displaying in list after running command python manage.py run server In Django I created two URLs to insert data and retrieve data but As I can check in database data is inserted properly in table but it is displaying in list after running command python manage.py run server -
How to change unique_together error message in django model?
Model: class MyModel(models.Model): field1 = models.CharField(max_length=50) field2 = models.CharField(max_length=50) class Meta: unique_together = ('field1', 'field2') Error: UNIQUE constraint failed: field1, field2 I want to change error mesaage to {'field2': 'This value is already exist'} OR How to override unique_error_message() in django model? I try this: def unique_error_message(self, model_class, unique_check): return ValidationError(message='My custom error message') But didn't work. -
Retrieve submitted data Django
I have created this dependent dropdown using plain HTML. When I click on submit, it redirects me to the next page where I have to run a python code based on the selection made in the previous page. I am unable to figure out how to retrieve the submitted data, any help? -
Get objects where (val1, val2) both in (other_val1, other_val2, ...)
Given the models below: class Language(models.Model): name = models.CharField(max_length=255, unique=True) class Profile(models.Model): languages = models.ManyToManyField(Language) class Job(models.Model): language1 = models.ForeignKey( Language, models.CASCADE, related_name='language1' ) language2 = models.ForeignKey( Language, models.CASCADE, related_name='language2' ) How to represent the following sql query to orm expression? with user_languages as (select language_id from core_profile_languages where profile_id = <profile-id>) select * from core_job where language1_id in (select * from user_languages) and language2_id in (select * from user_languages) -
Save generated image to ImageField model Django
Detected path traversal attempt in '/home/mrlonely/Desktop/lumen/lumen/media/thumbnail/6.jpeg' When i run this in the views.py: def generate_thumbnail(instance): post = Post.objects.get(pk=instance.pk) output = 'media/thumbnail/' + post.title + '.jpeg' filename_thumbnail = Path.joinpath(filename, output) try: ( ffmpeg .input(str(filename)+post.video.url, ss='00:00:20') .output(output, vframes=1) .overwrite_output() .run(capture_stdout=True, capture_stderr=True) ) with open(filename_thumbnail, 'rb') as file_handler: django_file = File(file_handler) post.thumbnail.save(filename_thumbnail, 'thumbnail/') except ffmpeg.Error as e: print(e.stderr.decode(), file=sys.stderr) sys.exit(1) I am trying to connect the ffmpeg generated thumbnail to the model ImageField on the Post model (instance is post) -
how can i post form object, correctly?
i am practicing CBV , so i thought to check if i can override methodes, well one of biggest problems is that idk how to use data(like data just submitted ), i wrote this code for a DetailView so i could see post and comments under it: class ArtDetailView(FormView, DetailView): model = Art form_class = CommentForm def get_context_data(self, **kwargs): context = super(ArtDetailView, self).get_context_data(**kwargs) context['time'] = timezone.now() context['form'] = self.get_form() return context def form_valid(self, form): form.instance.writer = self.request.user form.instance.text = self.post #form.instance.art = Art.objects.get(id=self.pk) form.save() return super().form_valid(form) def get_success_url(self) -> str: return reverse('pages:art_detail', args=(self.kwargs['pk'],)) forms.py: from django import forms from .models import Art, Comment class CommentForm(forms.ModelForm): class Meta(): model = Comment fields = ['text','art'] but when i post something it is in this shape:screen_shot(2nd comment) ,i think problem is withform.instance.text = self.post but i don't know how to fix it can you please also explain a little because all i want is to learn. and i tried to also add art as autofill(i added as comment) but wasn't successful, can you pls check it it too. -
Use Javascript to add row and html element with Django to get view dict but appear Error
Use Javascript to add row and html element with django get view dict show , but getting an error, the error shows django.template.exceptions.TemplateSyntaxError: Could not parse some characters: JourDt|"+i+"||date:'Y-m-d' i try use quotation mark Adjustment,still can't do it, what should i do? <script> $(document).ready(function () { var html = ""; for (i = 1 ; i < 5 ; i++) html += "<tr style="+"text-align: center;>" +"<td>"+i+"</td>" +"<td><input type="+"'date'"+"value="+"{{JourDt"+i+"|date:'Y-m-d'}}></td>"; $("#myTable").html(html); }); </script> -
Looking for a way to detect database changes using Django Channels
I am looking for a way to detect if there is data insertion happened in my database, i will use this to create a notification badge in real time so that the user wont need to refresh the page to see if there is new notifications. I am planning to use django channels but i cannot see any tutorials that will fit my need. I've tried to use timer but i don't think it is the best practice for this. -
How to create and save a model with multiselect values in Django
I am trying to create a model where I can assign multiple days of the week to a Customer through a form. However, when I try to save it I get the following error. django.db.utils.DataError: value too long for type character varying(2) I am using the django-multiselectfield package to create multiple select checkboxes. https://pypi.org/project/django-multiselectfield/ model.py from multiselectfield import MultiSelectField DAYS_OF_THE_WEEK_CHOICES = [ ('Mo', 'Monday'), ('Tu', 'Tuesday'), ('We', 'Wednesday'), ('Th', 'Thursday'), ('Fr', 'Friday'), ('Sa', 'Saturday'), ('Su', 'Sunday'), ] class Customer(models.Model): days_of_the_week = MultiSelectField(choices=DAYS_OF_THE_WEEK_CHOICES) forms.py RECURRINGDAYS = [ ('Mo','Monday'), ('Tu','Tuesday'), ('We','Wednesday'), ('Th','Thursday'), ('Fr','Friday'), ('Sa','Saturday'), ('Su','Sunday') ] class CustomerCreateForm(forms.Form): days_of_the_week = forms.MultipleChoiceField(required=False, choices=RECURRINGDAYS, widget=forms.CheckboxSelectMultiple(), label="Recurring Day(s)?") views.py from .models import Customer from .forms import CustomerCreateForm def create_customer(request): form = CustomerCreateForm(request.POST or None) if request.POST: if form.is_valid(): recurringDays = form.cleaned_data['days_of_the_week'] newCustomer = Customer( days_of_the_week = recurringDays ) newCustomer.save() return render(request, "customer.html", context) If someone fills out the form and selects Monday and Tuesday, how do I save that to the database Customer model? -
DRF foreign key field is empty when update the object
In Django Rest Framework this is the model: class Vehicle(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True) system = models.ForeignKey(System, on_delete=models.SET_NULL, null=True) vehicle_type = models.ForeignKey(VehicleType, on_delete=models.PROTECT, null=True) I created an object with both vehicle_type and system but when I try to update the object, vehicle_type is empty by default. how can I fill vehicle_type with instance data? -
VSC : font color does not chagnges
enter image description here As soon as i installed django, the situation above suddenly happend. The fontcolor that represents imported modules or variables does not change into appropriate ones and remains white. Still Django works but i cannot directly see it does how can i solve this problem? attempted to change settings but didn't find any solution i want to make VSC recognize class and variables precisely -
Django e-commerce checkout page does not want to display products in the HTML page
basket/models.py from decimal import Decimal from django.db import models, migrations from django.conf import settings from datetime import datetime from marketplace.models import prodProduct from member.models import Person class Basket(models.Model): class Meta: db_table = 'basket' productqty = models.IntegerField(default=0) productid = models.ForeignKey(prodProduct, on_delete=models.CASCADE) Person_fk = models.ForeignKey(Person, on_delete=models.CASCADE) def save(self): super().save() def get_subtotal_price(self, fk1): product = prodProduct.objects.get(pk=fk1) basket = Basket.objects.all() return sum(Decimal(product['productPrice']) * basket['productqty']) def get_total_price(self, fk1): product = prodProduct.objects.get(pk=fk1) basket = Basket.objects.all() subtotal = sum(Decimal(product['productPrice']) * basket['productqty']) if subtotal == 0: shipping = Decimal(0.00) else: shipping = Decimal(3.00) total = subtotal + Decimal(shipping) return total marketplace/models.py class prodProduct(models.Model): class Meta: db_table = 'prodProduct' productid = models.AutoField(primary_key=True) productName = models.CharField(max_length=255, blank=True) productDesc = models.CharField(max_length=1500,blank=True) productCategory = models.CharField(max_length=255, blank=True) productPrice = models.DecimalField(max_digits=4, decimal_places=2) productStock = models.IntegerField(default=0) productPhoto = models.ImageField(upload_to ='images/', null=True) productRating = models.IntegerField(default=0) timePosted = models.DateTimeField(default=datetime.now, blank=True) Person_fk = models.ForeignKey(Person, on_delete=models.CASCADE) def save(self): super().save() return self.productid def deleteProduct(self): super().delete() basket/summary.html {% block content %} <div class="container"> <div class="col-12"> <h1 class="h2">Your Basket</h1> </div> <div class="col-12"> <p>Manage your <b>items</b> in your basket</p> </div> <hr /> </div> <div class="container"> <div class="row g-3"> {% if allBasket.count == 0 %} <div class="col-12">Your basket is empty <a href="{% url 'MainMarketplace' %}">Shop</a></div> {% else %} <div class="col-12 bg-light p-3 d-flex justify-content-between"> …