Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I actually doesn't understand why {%if%} {%else%} doesn't work there. I just need to render this if author and username are equal
Actually, I am new in Django so I don't understand why if else statement doesn't work here. Is there anything super wrong with this code? {%extends 'main/base.html'%} {%block title%} {{ title }} {%endblock%} {%block content%} <div class="container-fluid"> <h2>{{user.first_name}}</h2> <p>{{user.second_name}}</p> <div class="col"> {%for recel in receipts%} {%if recel.author is user.username%} <h2>Receipt: {{recel.title}}</h2> <h4>Doctor: {{recel.author}}</h4> {%else%} <span></span> {%endif%} {%endfor%} </div> </div> {%endblock%} -
My Django Password encryption is not working
I have a User table that has some attributes where the Password is being stored as a String. I am trying to store it as an encrypted string using bcrypt, but for some reason it is not changing and the password continues to be the one before encryption. I have this in my settings.py: enter image description here And the method to add my User to the table is in views.py as this: enter image description here What am I doing wrong and how can I fix it? -
Django consuming Printfull API
I'm working on a project of one shop that consuming a Printful API, and I'm struggling to create a logic to pass the "Product" class on my model with the products variations. Following the scripts to get clean: The secret key is about one test store on printful, feel free to use. Printful Docs printful.py import requests import base64 url = 'https://api.printful.com/sync/products' s_key = 'xk7ov0my-t9vm-70z6:y491-2uyygexkkq6r' key = base64.b64encode(bytes(s_key, 'utf-8')) keyDecoded = key.decode('ascii') header = {'Authorization': 'Basic ' + keyDecoded} r = requests.get(url, headers=header) pack_json = r.json() class ProductList: id = [n for i in pack_json["result"] for k, n in i.items() if k == "id"] external_id = ([n for i in pack_json["result"] for k, n in i.items() if k == "external_id"]) name = ([n for i in pack_json["result"] for k, n in i.items() if k == "name"]) thumbnail_url = ([n for i in pack_json["result"] for k, n in i.items() if k == "thumbnail_url"]) str_id = [str(i) for i in id] id_name = dict(zip(str_id, name)) id_name_list = list(id_name.items()) models.py from django.db import models from django.db.models.deletion import CASCADE from core import printful import requests class SyncProducts(models.Model): ID_NAME = printful.ProductList.id_name_list title = models.CharField(max_length=200) name_id = models.CharField(max_length=200, choices=ID_NAME) def product_url(self): return f'https://api.printful.com/store/products/{self.name_id}' def __str__(self): d … -
For loops in a view
I am currently working on a rna to protein translator. To do that, I've created a class that does two things. Firstly, you input a dna chain and it gets translated into rna (this part works perfectly) Secondly, you get the rna chain translated into a protein (this part doesn't work). Here's the code for the class: class TranslatorView(View): template_name = 'main/translated.html' rna_mapper = { "a": "u", "t": "a", "c": "g", "g": "c" } amino_mapper={ "aat": "Asparagine", "aac": "Asparagine", "aaa": "Lysine", "aag": "Lysine", "act": "Threonine", "acc": "Threonine", "aca": "Threonine", "acg": "Threonine", "agt": "Serine", "agc": "Serine", "aga": "Arginine", "agg": "Arginine", "att": "Isoleucine", "atc": "Isoleucine", "ata": "Isoleucine", "atg": "Methionine", "cat": "Histidine", "cac": "Histidine", "caa": "Glutamine", "cag": "Glutamine", "cct": "Proline", "ccc": "Proline", "cca": "Proline", "ccg": "Proline", "cgt": "Arginine", "cgc": "Arginine", "cga": "Arginine", "cgg": "Arginine", "ctt": "Leucine", "ctc": "Leucine", "cta": "Leucine", "ctg": "Leucine", "gat": "Aspartic", "gac": "Aspartic", "gaa": "Glutamic", "gag": "Glutamic", "gct": "Alanine", "gcc": "Alanine", "gca": "Alanine", "gcg": "Alanine", "ggt": "Glycine", "ggc": "Glycine", "gga": "Glycine", "ggg": "Glycine", "gtt": "Valine", "gtc": "Valine", "gta": "Valine", "gtg": "Valine", "tat": "Tyrosine", "tac": "Tyrosine", "taa": "Stop", "tag": "Stop", "tct": "Serine", "tcc": "Serine", "tca": "Serine", "tcg": "Serine", "tgt": "Cysteine", "tgc": "Cysteine", "tga": "Stop", "tgg": "Tryptophan", "ttt": "Phenylalanine", "ttc": "Phenylalanine", "tta": … -
Uuser to be logged out after certain time period of inactivity using simple_jwt in django rest framework
I am using django rest framework and trying to implement a security solution. The user has to login again after certain time period of inactivity. Right now I am trying to manipulate django rest framework's settings and I updated the REFRESH_TOKEN_LIFETIME settings.py SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(minutes=30), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': True, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } -
Django phone number field not showing on admin page
I have created below model. from django.db import models from phone_field import PhoneField #pip install django-phone-field # Create your models here. class Profile(models.Model): dateofbirth = models.DateTimeField(null=True, blank=True) website = models.TextField(blank=True) degree = models.TextField(blank=True) phone = PhoneField(blank=True, help_text='Contact phone number') email = models.TextField(blank=True) city = models.TextField(blank=True) freelance = models.BooleanField(default=False) heading = models.TextField(blank=True) caption = models.TextField(blank=True) summary = models.TextField(blank=True) profile_captions_csv = models.TextField(blank=True) name = models.TextField(blank=True) webtitle = models.TextField(blank=True) def __str__(self): return self.heading To support the phone number field, I installed this. pip install django-phone-field The model is migrated but when I try to access it on admin page, I am getting error as template not found. My admin.py from django.contrib import admin from .models import Profile # Register your models here. class ProfileAdmin(admin.ModelAdmin): pass admin.site.register(Profile) Error: Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: C:\Users\UdayKiranReddy\AppData\Local\Programs\Python\Python38\lib\site-packages\django\forms\templates\phone_field\phone_widget.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\UdayKiranReddy\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\admin\templates\phone_field\phone_widget.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\UdayKiranReddy\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\auth\templates\phone_field\phone_widget.html (Source does not exist) django.template.loaders.app_directories.Loader: D:\my resume\UdayResume\homepage\templates\phone_field\phone_widget.html (Source does not exist) -
How to use NASA API with satellite layer in python django?
Currently, I am using the NASA API python package. I am able to retrieve the images by providing longitude and latitude. But I want the map location image in a satellite filter. from django.shortcuts import render from django.shortcuts import render,get_object_or_404,redirect,HttpResponse from nasaapi import Client # Create your views here. def home(request): api = 'CONSIDER MY API KEY HERE' lat = 32.466259415511644 lon = 35.48680851545021 date = '2017-10-10' nasa = Client(api) obj = nasa.earth(lat,lon,date=None) print(obj) return render(request,'home.html',{'context':obj}) -
Django Admin model create new instance instead of update
I've multiple models in my Django project but only this given below model creating another instance on update instead of save. This is happening in Django's Admin panel, not on my custom UI. When I remove my save() method then it works fine but this way I won't be able to create slug. Does anybody know what I'm doing wrong in here class Course(models.Model): title = models.CharField(max_length=200) user = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='category') slug = models.SlugField(max_length=200, unique=True, primary_key=True, auto_created=False) short_description = models.TextField(blank=False, max_length=60) description = models.TextField(blank=False) outcome = models.CharField(max_length=200) requirements = models.CharField(max_length=200) language = models.CharField(max_length=200) price = models.FloatField(validators=[MinValueValidator(9.99)]) level = models.CharField(max_length=20) application_link = models.URLField(max_length=1000, blank=True, null=True) brochure = models.FileField(upload_to='brochures/', blank=True, null=True) thumbnail = models.ImageField(upload_to='thumbnails/') video_url = models.CharField(max_length=100) is_session_available = models.BooleanField(default=False) session_url = models.CharField(max_length=250, default='') is_published = models.BooleanField(default=True) created_at = models.DateTimeField(default=now) updated_at = models.DateTimeField(default=now) def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Course, self).save(*args, **kwargs) -
My Python class feels very excessive. Is there a shorter way to do this?
I can't seem to find a way to research this. I have this Size class that buckets various size choices into common categories (small, medium, large, etc...). As a result, I ended up with this ridiculously long enumeration of sizes that I've defined. While it works, I was still wondering if there was a smarter way I could have executed this. Are TextChoices really the best way? class Size(models.TextChoices): xs = "xs" x_small = "x-small" xsmall = "xsmall" s00 = "00" s0 = "0" s1 = "1" s2 = "2" w23 = "w23" w24 = "w24" s = "s" sm = "sm" small = "small" s3 = "3" s4 = "4" s5 = "5" s6 = "6" w25 = "w25" w26 = "w26" m = "m" md = "md" med = "med" medium = "medium" s7 = "7" s8 = "8" s9 = "9" s10 = "10" w27 = "w27" w28 = "w28" l = "l" lg = "lg" large = "large" s11 = "11" s12 = "12" s13 = "13" s14 = "14" w29 = "w29" w30 = "w30" s1x = "1X" s1x = "1XL" xl = "xl" x_large = "x-large" xlarge = "xlarge" s15 = "15" s16 = … -
creating a list of known faces for the face recognition library
i'm trying to integrate face recognition library to work with a django project, as the code is shown here based on the documentation: i have to specify the image path and [known face_encodings] and [known_face_names] inside the function or the script # Get a reference to webcam #0 (the default one) video_capture = cv2.VideoCapture(0) # Load a sample picture and learn how to recognize it. image_of_yahya = face_recognition.load_image_file('../media/yahya_stihi.jpg') yahya_face_encoding = face_recognition.face_encodings(image_of_yahya)[0] # Load a second sample picture and learn how to recognize it. obama_image = face_recognition.load_image_file("./images/obama.jpeg") obama_face_encoding = face_recognition.face_encodings(obama_image)[0] image_of_steve = face_recognition.load_image_file('./images/Steve Jobs.jpg') steve_face_encoding = face_recognition.face_encodings(image_of_steve)[0] image_of_ahmed = face_recognition.load_image_file('../media/ahmed_bouchfirat.jpg') ahmed_face_encoding = face_recognition.face_encodings(image_of_ahmed)[0] # Create arrays of known face encodings and their names known_face_encodings = [ obama_face_encoding, steve_face_encoding, yahya_face_encoding, ahmed_face_encoding, ] known_face_names = [ "Barack Obama", "Steve Jobs", "yahya stihi", "ahmed bouchfirat" ] as i started to add more faces i noticed that my code is getting ugly and not efficient and slow now i'm trying to kinda put this section on separate file and load the known faces text only and maybe a for loop so i can create a queryset for every name in that list and that file can be modified while adding a new user so is … -
Sum data in serializer Django
I would like sum data from nested object. My model: class Diet(models.Model): day = models.IntegerField() meals = models.ManyToManyField(Meal) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f'{self.day} - {self.user}' My viewset: class DietViewSet(viewsets.ModelViewSet): queryset = Diet.objects.all() serializer_class = DietSerializer pagination_class = None def get_queryset(self): if self.action == 'list': self.queryset = Diet.objects.filter(user=self.request.user).order_by('day') else: self.queryset = Diet.objects.all().order_by('day') return super(DietViewSet, self).get_queryset() def get_permissions(self): if self.action in ['list', 'retrieve']: self.permission_classes = [permissions.AllowAny] else: self.permission_classes = [IsDietician] return super(DietViewSet, self).get_permissions() My serializers: class MealSerializer(serializers.ModelSerializer): class Meta: model = models.Meal fields = '__all__' class DietSerializer(serializers.ModelSerializer): def to_representation(self, instance): result = super(DietSerializer, self).to_representation(instance) result['meals'] = MealSerializer(instance.meals, many=True).data return result class Meta: model = models.Diet fields = '__all__' Now I would like add total_kcal which will be calculate by data from meals. I tried did it by kcal = serializers.MethodSerializerField() and def get_kcal(self, obj) but I don't know how can I get data from serialized objects in to_representation. Example response: [ { "id":1, "day":1, "user":1, "meals":[ { "id":4, "name":"Rise", "description":"", "kcal":150.0, "protein":3.0, "fat":0.0, "carbs":28.0 }, { "id":5, "name":"Chocoloate", "description":"", "kcal":200.0, "protein":0.0, "fat":0.0, "carbs":100.0 } ] } ] -
My Django model for video upload saying “ValueError”
I am trying to write a small blog where I can be uploading my videos for public download but am getting a server error message when I try click on any video for details. Below is the error that I'm getting when Debug is set to True ValueError at /video/lagos-anthem/ Sample larger than population or is negative Request Method: GET Request URL: https://www.majestylink.com/video/lagos-anthem/ Django Version: 3.1.2 Exception Type: ValueError Exception Value: Sample larger than population or is negative Exception Location: /home/majestyempire/.virtualenvs/majestyenv/lib/python3.7/random.py, line 321, in sample Python Executable: /usr/local/bin/uwsgi Python Version: 3.7.5 Python Path: ['/var/www', '.', '', '/var/www', '/home/majestyempire/.virtualenvs/majestyenv/lib/python37.zip', '/home/majestyempire/.virtualenvs/majestyenv/lib/python3.7', '/home/majestyempire/.virtualenvs/majestyenv/lib/python3.7/lib-dynload', '/usr/lib/python3.7', '/home/majestyempire/.virtualenvs/majestyenv/lib/python3.7/site-packages', '/home/majestyempire/musicblog/myblog'] Server time: Sat, 28 Nov 2020 13:49:35 +0100 Below is my models.py class Video(models.Model): CATEGORY_CHOICES = ( ('Music', 'Music'), ('Movies', 'Movies'), ) artist = models.CharField(max_length=200, unique=True) category = models.CharField(max_length=30, choices=CATEGORY_CHOICES, default='Music') title = models.CharField(max_length=200, unique=True) slug = models.SlugField(default='', blank=True, unique=True) thumbnail = models.ImageField(blank=False) video_file = models.FileField(default='') uploaded_date = models.DateTimeField(default=timezone.now) objects = PostManager() class Meta: ordering = ['-uploaded_date'] def save(self): self.uploaded_date = timezone.now() self.slug = slugify(self.title) super(Video, self).save() def __str__(self): return self.title def get_absolute_url(self): return reverse('video:detail', kwargs={'slug': self.slug}) This is the post_detail view def post_detail(request, slug): random_posts = random.sample(list(Video.objects.all()), 2) vid = get_object_or_404(Video, slug=slug) comments = Comment.objects.filter(post=vid) is_liked … -
filtering with django rest framework
I'm using django rest framework in my project and I want to have filtering on my products . i filter products with category name and popular . but i want to filter products that have discount too . this is my model: class Product(models.Model): category = models.ManyToManyField(Category, related_name='products') name = models.CharField(max_length=500) slug = models.SlugField(max_length=500, allow_unicode=True, unique=True) image = models.ImageField(upload_to='products_pic/%Y/%m/%d/', null=True, blank=True) description = models.TextField(null=True, blank=True) price = models.PositiveIntegerField() discount = models.PositiveIntegerField(null=True, blank=True) available = models.BooleanField(default=True) popular = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) comments = GenericRelation(Comment) class Meta: ordering = ('-created',) def __str__(self): return self.name there is a problem here. discount is a integer field and i want to filter products with boolean discount. i mean i want to filter products that have discount or not. it is not important how much discount they have. this is my view: class search(generics.ListAPIView): queryset = Product.objects.filter(available=True) serializer_class = ProductSerializer permission_classes = (permissions.AllowAny,) filter_backends = [DjangoFilterBackend, filters.SearchFilter] filter_fields = ['category__name', 'popular'] search_fields = ['name', 'category__name', 'description'] -
Django this page is not rendering?
the page is keep giving me this error page is not rendering. I am not getting any error in the terminal. here is my view: class Blog_list_View(View): model = Blog template_name = 'blog.html' paginated_by = 1 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) blog_list = Blog.objects.all() category_count = get_category_count() latest = Blog.objects.order_by('-timestamp')[0:3] paginator = Paginator(blog_list, self.paginated_by) page = self.request.GET.get('page') try: blog = paginator.page(page) except PageNotAnInteger: blog = paginator.page(1) except EmptyPage: blog = paginator.page(paginator.num_pages) context['latest'] = latest, context['form'] = form, context['category_count'] = category_count, return context here is urls.py: from Blog.views import Blog_View urlpatterns = [ path('admin/', admin.site.urls), path('blog/', Blog_View.as_view(), name="blog-view"), -
Setting up gitlab CI with simple django project
I have a very simple django project with a few unit tests on it and I would like to set up Gitlab to run those tests evry time I make a new commit. I use sqlite3 for my database (I plan to change later, but for now I want to keep it simple) and I stored some of my settings variable in a .env file. Here is my .gitlab-ci.yml file (I used the default file proposed by gitlab and removed what I thought I didn't need) : image: python:latest variables: SECRET_KEY: "this-is-my-secret-key" DEBUG: "True" ALLOWED_HOSTS: "['*']" DB_ENGINE: "django.db.backends.sqlite3" DB_NAME: "test_database.sqlite3" STATIC_URL: "/static/" cache: paths: - ~/.cache/pip/ before_script: - python -V - pip install -r requirements.txt test: script: - cd backend - python manage.py test but when I commit, I get this error $ python manage.py test /usr/local/lib/python3.9/site-packages/environ/environ.py:628: UserWarning: /builds/romainros/ynoverflow/backend/ynoverflow/.env doesn't exist - if you're not configuring your environment separately, create one. warnings.warn( Creating test database for alias 'default'... Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/test.py", line 53, in handle failures = test_runner.run_tests(test_labels) File "/usr/local/lib/python3.9/site-packages/django/test/runner.py", line 629, in run_tests old_config = self.setup_databases(aliases=databases) File … -
translate rna to protein
I am currently working on a rna to protein translator. To do that, I've created a class that does two things. Firstly, you input a dna chain and it gets translated into rna (this part works perfectly) Secondly, you get the rna chain translated into a protein (this part doesn't work). Here's the code for the class: class TranslatorView(View): template_name = 'main/translated.html' rna_mapper = { "a": "u", "t": "a", "c": "g", "g": "c" } amino_mapper={ "aat": "Asparagine", "aac": "Asparagine", "aaa": "Lysine", "aag": "Lysine", "act": "Threonine", "acc": "Threonine", "aca": "Threonine", "acg": "Threonine", "agt": "Serine", "agc": "Serine", "aga": "Arginine", "agg": "Arginine", "att": "Isoleucine", "atc": "Isoleucine", "ata": "Isoleucine", "atg": "Methionine", "cat": "Histidine", "cac": "Histidine", "caa": "Glutamine", "cag": "Glutamine", "cct": "Proline", "ccc": "Proline", "cca": "Proline", "ccg": "Proline", "cgt": "Arginine", "cgc": "Arginine", "cga": "Arginine", "cgg": "Arginine", "ctt": "Leucine", "ctc": "Leucine", "cta": "Leucine", "ctg": "Leucine", "gat": "Aspartic", "gac": "Aspartic", "gaa": "Glutamic", "gag": "Glutamic", "gct": "Alanine", "gcc": "Alanine", "gca": "Alanine", "gcg": "Alanine", "ggt": "Glycine", "ggc": "Glycine", "gga": "Glycine", "ggg": "Glycine", "gtt": "Valine", "gtc": "Valine", "gta": "Valine", "gtg": "Valine", "tat": "Tyrosine", "tac": "Tyrosine", "taa": "Stop", "tag": "Stop", "tct": "Serine", "tcc": "Serine", "tca": "Serine", "tcg": "Serine", "tgt": "Cysteine", "tgc": "Cysteine", "tga": "Stop", "tgg": "Tryptophan", "ttt": "Phenylalanine", "ttc": "Phenylalanine", "tta": … -
How to show validation error in django admin page with post_save signal?
I need to show validation error in django admin page like a clean function for a django model my post_save function: @receiver(models.signals.post_save, sender=Counter) def execute_after_save(sender, instance, created, *args, **kwargs): counter = Counter.objects.filter(order_id=instance.order_id).values('product_id').annotate(Count('pk')) counter = counter.values('pk__count').get()['pk__count'] if counter is None: counter = 0 if counter > 1: raise ValidationError("Error here") -
Need help in Django Templates(using forloops)
I have 3 models namely Uses, Customer and Services.I have a query whose result is stored in the variable count. This is the query counts = Services.objects.filter(uses__customer=customer).annotate(times_used=Count('uses')) Each count[x] has a variable,x ranges from 0 to infinity. I have used a for loop in my html to get all the Services which I have passed through context in views. Now I need to get unique value of count for each service. How can I do this. Here is my html code <table class='table table-bordered' id='dataTable' width='100%' cellspacing='0'> <thead class='bg-primary'> <tr class='text-white'> <th>Service-Id</th> <th>Service-name</th> <th>Count</th> <th>Price</th> </tr> </thead> <tbody class="text-dark"> <tr>{% for service in services %} <td>{{ service.id }}</td> <td>{{ service.service_name }}</td> <td>#code for printing code# </td> <td>{{ service.price }}</td> </tr>{% endfor %} </tbody> </table> -
Django: How to pass a variable from view to forms?
I have view document and I would like to pass the my_number variable to DocumentForm in order to define what the form should look like. **views.py** def document(request, my_number): form = DocumentForm(request.POST or None) if form.is_valid(): form.save() return redirect(f'/index/') return render(request, 'document.html', {'form': form}) I think I have to pass the my_number for example in such a way: form = DocumentForm(request.POST or None, number=my_number) And in forms.py i have: **forms.py** class DocumentForm(ModelForm): class Meta: model = Document fields = [] person = Person.objects.get(id=number) choices = person.elements for choice in choices: if choice == '1': fields.append('choice_1') if choice == '2': fields.append('choice_2') But I don't know how to call number in: class Meta and in person = Person.objects.get(id=number). I will be very grateful for any suggestions. -
Django Bootstrap Accordion needs double click to expand
When I click the accordion the first time nothing happens. When I click it a second time, it opens and then closes immediately! It's like the second click sends both. Here's my template: {% for category in challenges_by_category_list %} {% if category %} <h2>{{ category.title }}</h2> <div class="accordion" id="accordion{{category.title}}"> {% for challenge in category.challenge_set.all %} <div class="card"> <div class="card-header" id="heading{{challenge.id}}"> <h2 class="mb-0"> <button class="btn btn-link btn-block text-left" type="button" data-toggle="collapse" data-target="#collapse{{challenge.id}}" aria-expanded="true" aria-controls="collapse{{challenge.id}}"> {{ challenge.question_text }} </button> </h2> </div> <div id="collapse{{challenge.id}}" class="collapse in" aria-labelledby="heading{{challenge.id}}" data-parent="#accordion{{category.title}}"> <div class="card-body"> Anim pariatur cliche reprehenderit, enim eiusmod high </div> </div> {% endfor %} </div> {% endif %} {% endfor %} I wondered whether it's something to do with including bootstrap twice? But here's my base.html includes: <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <!-- Latest compiled JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> I've also installed crispy_forms which uses bootstrap, I don't know if that's relevant. -
'QueryDict' object is not callable
when i want run a code, create user in my blog, i get error 500 and 'QueryDict' object is not callable and problem in this row : data = form.data() my code below: def create_post(request): if request.method == 'POST': form = PostFormClass(request.POST) if form.is_valid(): form.save() data = form.data() dump = json.dumps(data) return JsonResponse(dump, content_type="application/json") return JsonResponse({"message": "invalid form"}) else: form = PostFormClass() args = {'form': form} return JsonResponse(args, content_type="application/json") -
My Django model for video upload saying "ValueError"
I am trying to write a small blog where I can be uploading my videos for public download but am getting a server error message when I try click on any video for details. Below is the error that I'm getting when Debug is set to True ValueError at /video/lagos-anthem/ Sample larger than population or is negative Request Method: GET Request URL: https://www.majestylink.com/video/lagos-anthem/ Django Version: 3.1.2 Exception Type: ValueError Exception Value: Sample larger than population or is negative Exception Location: /home/majestyempire/.virtualenvs/majestyenv/lib/python3.7/random.py, line 321, in sample Python Executable: /usr/local/bin/uwsgi Python Version: 3.7.5 Python Path: ['/var/www', '.', '', '/var/www', '/home/majestyempire/.virtualenvs/majestyenv/lib/python37.zip', '/home/majestyempire/.virtualenvs/majestyenv/lib/python3.7', '/home/majestyempire/.virtualenvs/majestyenv/lib/python3.7/lib-dynload', '/usr/lib/python3.7', '/home/majestyempire/.virtualenvs/majestyenv/lib/python3.7/site-packages', '/home/majestyempire/musicblog/myblog'] Server time: Sat, 28 Nov 2020 13:49:35 +0100 -
How to retrieve necessary fields from ModelForms and pass them to views.py properly?
Short background of whole idea: I'm trying to create landing page and for backend I use Python/Django3 framework. I need to create form with such fields as name, surname, email, mobile number and address of customer. I've decided to save all the information that the user enters in the database, and also send it to my email. In order to connect database to forms I use ModelForms in forms.py section (all the required code will be shown below). In order to connect my email to form I use send_mail function from django.core.mail. So when a user fills out his form, he is redirected to the 'thank you' page and all the information from the form is saved in the database and sent to my email. But when I finally wrote the code and started to test functionality, I found out that when I hit 'submit' form button, error <type object 'ClientInfoForm' has no attribute 'cleaned_data'> is raised. I suppose, that method cleaned_data is wrong in my case and I have to replace it with something else but I don't know with what exactly. All the code will be placed below and any help will be helpful. Thank you! Models.py file … -
Using while loop with counter in django template
I need to put a counter in while loop in template. So I did: <tbody> {% with count=1 %} {% while count <={{orders_count}}: %} {% for order in orders %} <tr> <td style="width:5%;"></td> <td>{{count}}</td> <td>{{order.name}}</td> </tr> {% count+=1 %} {% endfor %} {% endwhile %} {% endwith %} </tbody> But finaly I have the following error: Invalid block tag on line 216: 'while', expected 'endwith'. Did you forget to register or load this tag? -
DRF ManytoMany filtering on related model, in subquery?
There are two models, a Page model and a Banner model, which are manyToMany related. The parameters API is twitched, which returns a list of pages and banners for each page. The Banner model has a field is_show by which you need to additionally filter the list of banners, i.e. in the admin panel, the banner can be selected for the model, but if is_show = False, then you do not need to return it to the API. views class PagesListView(generics.ListAPIView, viewsets.GenericViewSet): queryset = Page.objects.all() serializer_class = PageSerializer models class Banner(models.Model): title = models.CharField(verbose_name='Заголовок', max_length=255, null=True, blank=True) is_show = models.BooleanField(verbose_name='Управление отображением', null=False) pages = models.ManyToManyField( Page, blank=True, related_name='banners') class Page(models.Model): name = models.CharField(max_length=255, null=True, blank=True) serializers class BannerSerializer(serializers.ModelSerializer): class Meta: model = Banner fields = '__all__' class PageSerializer(serializers.ModelSerializer): banners = BannerSerializer(read_only=True, many=True) class Meta: model = Page fields = '__all__' The question is how to filter Banner by is_show field? If you just override the queryset for the view like this: queryset = Page.objects.filters(banners__is_show=True) then this is not the desired behavior. In this way, I am filtering the Page list, and I need to "wedge" into filtering the Banner list.