Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Stripe; Webhook that triggers when the current subscription gets ended (not cancelled)
I know that there is a webhook type customer.subscription.deleted that gets triggered when a user cancels the subscription (that is they don't want the subscription to be auto-renewed after it ends) so at this webhook event, we just update the users subscription state to cancel but they still have the subscription active (and that is expected) but is there any webhook event that gets triggered when the subscription ends or we have to do that manually? I saw this webhook event but i'm not sure if this is the one I'm searching for subscription_schedule.completed Any guidance would be helpful, thank you :) -
Display the number of comments of each post related to the same post in django
Hello friends I am building a blog and I have encountered a problem. My problem is that when I want to display the number of comments for each post, on the main page of the blog number of comments displays all posts that have comments, but the number of comments for each post is the same. In the event that post 2 has 3 comments and the other has 1 comment. You can see in this picture. Image This is my models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) name = models.CharField(max_length=100) email = models.EmailField() comment = models.CharField(max_length=500) active = models.BooleanField(default=False) created_date = models.DateTimeField(auto_now_add=True) def __str__(self): return "{} by {}".format(self.comment, self.name) This is my views.py def post_list(request): posts = models.Post.objects.filter(status='published') paginator = Paginator(posts, 4) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) comment_count = models.Comment.objects.filter(active=True).count() context = { 'page_obj': page_obj, 'comment_count': comment_count, } # print(posts) return render(request, "post_list.html", context=context) And this too post_list.html <article class="col-12 col-md-6 tm-post"> <hr class="tm-hr-primary"> <a href="{{ post.get_absolute_url }}" class="effect-lily tm-post-link tm-pt-60"> <div class="tm-post-link-inner"> <img src="/{{ post.image }}/" alt="Image" class="img-fluid"> </div> <h2 class="tm-pt-30 tm-color-primary tm-post-title">{{ post.title }}</h2> </a> <p class="tm-pt-30"> {{ post.body|slice:254 }} </p> <div class="d-flex justify-content-between tm-pt-45"> <span class="tm-color-primary">Travel . Events</span> <span class="tm-color-primary">{{ post.created_date.year }}/{{ post.created_date.month }}/{{ post.created_date.day … -
trying to post form data to django rest API by react using axios error buy saying The submitted data was not a file. Check the encodon
I am trying to send the form data( image) using react and Axios to rest API to Django data base I leading an error {photo: ["The submitted data was not a file. Check the encoding type on the form."]}photo ["The submitted data was not a file. Check the encoding type on the form."] "The submitted data was not a file. Check the encoding type on the form." import React, { useState } from "react"; import InputChar from "./SmallComponents/InputChar"; import InputNum from "./SmallComponents/InputNum"; import axios from "axios"; function CreateProduct() { const [productData, setProductData] = useState({ name: "", producttype: "", color: "", brand: "", desc: "", gender: "", offer: 0, price: 0, size: "", photo: "", }); function handleParentCharChange(featureName, featureValue) { setProductData((preProductData) => { return { ...preProductData, [featureName]: featureValue, }; }); console.log("------product data ----", featureName, featureValue); console.log("product data", productData); } function handleFormData(event) { setProductData((preProductData) => { return { ...preProductData, [event.target.name]: event.target.value, }; }); console.log("product data", productData); } function handleImageData(event) { const file = event.target.files[0]; // accessing file console.log("++++++++++image+++++++++++",file); setProductData((preProductData) => { return { ...preProductData, "photo" : file, } }) } function submitHandler(event) { event.preventDefault(); axios .post("http://127.0.0.1:8000/product/productcreate/", productData) .then((response) => { console.log("data is stored", response); }) .catch((error) => { console.log("data is not store", … -
IN ADMIN PANEL __str__ returned non-string (type NoneType)
im new to django tryna build up ecommerce project for education purposes. i got this error "str returned non-string (type NoneType)" from admin panel, when try view/change order or orderItem. I try to return str(self)I cant find error, pls guys help me fix it. I almost google all, but i dont understand how to can be type error if i return str(). Pls guys help my find they way to fix it from django.core.validators import RegexValidator from django.db import models from authentication.models import Customer from catalog.models import Product # Create your models here. class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True) date_order = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=True) transaction_id = models.CharField(max_length=200, null=True, blank=True) def __str__(self): return str(self.transaction_id) @property def shipping(self): shipping = False orderitems = self.orderitem_set.all() for i in orderitems: if i.product.digital == False: shipping = True return shipping @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum([item.quantity for item in orderitems]) return total class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) @property def get_total(self): total = self.product.price * self.quantity return total class … -
Render html form in django with forms.py
I have django web application with authentication system in it. I have user registration view, customer model and UserCreationForm in forms.py: class CustomerSignUpForm(UserCreationForm): first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) # phone_number = forms.CharField(required=True) # location = forms.CharField(required=True) class Meta(UserCreationForm.Meta): model = User @transaction.atomic def save(self): user = super().save(commit=False) user.is_customer = True user.first_name = self.cleaned_data.get('first_name') user.last_name = self.cleaned_data.get('last_name') print(user.last_name) user.save() customer = Customer.objects.create(user=user) # customer.phone_number=self.cleaned_data.get('phone_number') # customer.location=self.cleaned_data.get('location') customer.save() return user My model looks like this: ... first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) phone_number = models.CharField(max_length=20) location = models.CharField(max_length=20) I render form in my customer_register.html: ... <section> <div class="container"> <div class="row"> <div class="col-md-6 mx-auto"> <div class="card"> <div class="card-header text-black"> <h2>Register</h2> </div> <div class="card-body"> <form action="{% url 'customer_register' %}" method="POST" novalidate> {% csrf_token %} {% for field in form.visible_fields %} <div class="form-group"> {{ field.label_tag }} {% render_field field class="form-control" %} {% for error in field.errors %} <span style="color:red">{{ error }}</span> {% endfor %} {% endfor %} </div> </form> </div> </div> </div> </div> </div> </div> </section> ... It doesn't look very pretty though. What I want to do is to replace my form in customer_register.html with new form in which I wouldn't use widget_tweaks but just html. -
Django media url from model
I'm working on a simple blog, I have this model for the blog post: class BlogPost(models.Model): title = models.CharField(max_length=150, unique=True) body = models.TextField() cover_image = models.ImageField(upload_to='blogposts/') created_on = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) category = models.ManyToManyField('PostCategory', related_name='posts') slug = models.SlugField(null=True, unique=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("blog_detail", kwargs={"slug": self.slug}) In the settings file, I have the following configuration for static and media files: STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') STATIC_ROOT = os.path.join(BASE_DIR, 'static/') I'm creating the blog models and views in a separate app I named "blog" I'm using a Django classed-based list view to display the posts on the page: class BlogListView(ListView): model = BlogPost template_name = "blog/blog_list.html" And I have the URL files working just fine: The problem is in displaying it in my template view, primarily for the post's cover image: {% for post in object_list %} <!-- Single Blog Item --> <div class="single-blog-item style-2 d-flex flex-wrap align-items-center mb-50"> <!-- Blog Thumbnail --> <div class="blog-thumbnail"> <a href="{{ post.get_absolute_url }}"> <img src="{{ post.cover_image }}" alt=""> </a> </div> <!-- Blog Content --> <div class="blog-content"> <a href="{{ post.get_absolute_url }}" class="post-title">{{ post.title }}</a> <p>We'll come back to this...</p> <div class="post-meta"> <a href="#"><i class="icon_clock_alt"></i> {{ post.created_on }}</a> … -
Django - One to One field bug not saving data without error
I am currently experiencing an issue with a one-to-one field in Django where the data was not stored after assigning value and save call is successful without any error. class Model1(models.Model): field1 = models.OneToOneField(Model1, on_delete=models.SET_NULL, null=True, blank=True, default=None) # Some other fields here def link_item(self, model2_id): field1 = Model2.objects.get(id=model2_id) self.field1 = field1 self.save() When I use the link_item of the model from the python shell it was updating the field but when it was used on the normal process the save call is successfully called but when I checked the value again in the shell it didn't update the field1. I have almost 10 million rows of data for Model1 and Model2, I'm not sure if it related to the issue but maybe it could help. -
Django raises set-returning functions are not allowed in WHERE with annotated value
I need to query orders where the shipping address's postcode is between a certain range. In order to do this, I have to cast the postcode (charfield) to a integer by removing the non numeric values. I have written this database function for that which works: class NumericPostcode(models.Func): """ Removes characters from field and converts to integer """ function = "REGEXP_MATCHES" template = "CAST( (%(function)s(%(expressions)s, '\\d+'))[1] as INTEGER )" output_field = models.IntegerField() Then I do the following query: orders_qs = Order.objects.annotate( numeric_postcode=NumericPostcode(models.F("shipping_address__postcode")) ).filter(self.get_range_query()) The get_range_query is a method that builds a dynamic query: def get_range_query(self): """ Build the range query dynamically based on all postcode ranges linked to this transporter https://docs.djangoproject.com/en/dev/ref/models/querysets/#range """ query = models.Q() for postcode_range in self.postcode_ranges.all(): query |= models.Q(numeric_postcode__range=(postcode_range.min_postcode, postcode_range.max_postcode)) return query However, this query raises the error: NotSupportedError at /admin/shop/reports/ set-returning functions are not allowed in WHERE Without the .filter(self.get_range_query()), I can print the annotated field fine and it also works. The raw SQL query is as follows: SELECT "order_order"."id", "order_order"."number", "order_order"."site_id", "order_order"."basket_id", "order_order"."user_id", "order_order"."billing_address_id", "order_order"."currency", "order_order"."total_incl_tax", "order_order"."total_excl_tax", "order_order"."shipping_incl_tax", "order_order"."shipping_excl_tax", "order_order"."shipping_address_id", "order_order"."shipping_method", "order_order"."shipping_code", "order_order"."status", "order_order"."guest_email", "order_order"."date_placed", "order_order"."delivery_time_text", "order_order"."delivery_time_days", cast( (Regexp_matches("order_shippingaddress"."postcode", '\d+'))[1] AS INTEGER ) AS "numeric_postcode" FROM "order_order" LEFT OUTER JOIN "order_shippingaddress" ON ( "order_order"."shipping_address_id" = … -
Python Http Client requests
I would like to retrieve product data using the POST method and passing it the security key on the headers I get an HTTP 400 error def api(request): headers={'content-type':'application/json','security-key': 'valu-key'} url = 'http://api-content/product/GetProduct' x = requests.post(url, headers = headers) content=x.status_code return HttpResponse(content) -
Docker Django Postgres FATAL: password authentication failed for user "postgres
I am dockerizing my Django app. My configs are the following: csgo.env POSTGRES_NAME='postgres' POSTGRES_USER='postgres' POSTGRES_PASSWORD='postgres' POSTGRES_HOST='postgres_db' POSTGRES_PORT='5432' settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.getenv('POSTGRES_NAME', 'postgres'), 'USER': os.getenv('POSTGRES_USER', 'postgres'), 'PASSWORD': os.getenv('POSTGRES_PASSWORD', 'postgres'), 'HOST': os.getenv('POSTGRES_HOST', 'postgres_db'), 'PORT': os.getenv('POSTGRES_PORT', '5432'), } } docker-compose.yml version: '3' services: web: build: context: . dockerfile: Dockerfile env_file: - csgo.env ports: - '8000:8000' volumes: - .:/code depends_on: - postgres_db postgres_db: image: postgres:13 restart: always ports: - '5432:5432' env_file: - csgo.env environment: - POSTGRES_NAME='postgres' - POSTGRES_USER='postgres' - POSTGRES_PASSWORD='postgres' - POSTGRES_HOST='postgres_db' - POSTGRES_PORT='5432' When I run docker-compose up, I get the typical auth error django.db.utils.OperationalError: FATAL: password authentication failed for user "postgres" and I am readdly stressed of it. I have been looking for a typo a day long and haven't figured it out. Please help me to debug! Note: I know that this kind of questions are overflowed on the Internet. My post is about finding a typo or a mechanical mistake by me. Thanks for understanding and not assigning the post as a duplicate one! -
KeyError: '__module__' when creating dynamically proxy models
I want to create dynamically proxy models with this code: from django.db import models class BaseId(models.Model): def __str__(self): return self.nom class Meta: app_label = 'sae' abstract = True NOMENCL_LIST = ['CAT', 'CATR', 'CCR', 'ESPIC', 'GRP', 'MFT', 'NAT', 'PERSO', 'STJ', 'STJR'] class Nomenclature(BaseId): code = models.CharField(max_length=20, unique=True) nom = models.CharField( max_length=250) class Valeurs_nomenclature(BaseId): nomenclature = models.ForeignKey(Nomenclature, on_delete=models.PROTECT, related_name='valeurs') code = models.CharField(max_length=20) nom = models.CharField(max_length=250) class NomenclatureManager(models.Manager): def get_queryset(self): qs = super().get_queryset() return qs.filter(nomenclature__code=qs.model.__name__) for nomencl in NOMENCL_LIST: if nomencl not in globals(): meta = type('Meta', (BaseId.Meta,), { 'proxy':True }) model = type(nomencl, (Valeurs_nomenclature,), # this line causes the error { 'Meta':meta, 'objects':NomenclatureManager }) globals()[nomencl] = model This code raises a KeyError the before last line: module = attrs.pop("__module__") KeyError: '__module__' When I set explicitly "module", it works : model = type(nomencl, (Valeurs_nomenclature,), { 'Meta':meta, 'objects':NomenclatureManager, '__module__':'sae.models.id_models' }) My question: in what circumstance 'module' is set implicitly or not ? -
Django Static files Page not found (404)
I am trying to create a website using Django and in my models.py I am using Django's ImageField(upload_to=''), but these files are not being uploaded to their location and I don't know why. That file is empty. So I am getting this error Page not found (404) at http://127.0.0.1:8000/class/instructor_pics/2_c4iU33j.jpg. The other static files are fine like carousel banner and everything but these files are not being uploaded. What should I change to make this work? My models.py: class Course(models.Model): title = models.CharField(max_length=100) image = models.ImageField(upload_to='class/instructor_pics', null=True) instructor = models.CharField(max_length=100) instructor_image = models.ImageField(upload_to='class/instructor_pics', null=True) enrolled_students = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='enrolled_students', blank=True) slug = models.SlugField(max_length=200, unique=True) description = models.TextField(max_length=300, null=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created'] def __str__(self): return self.title def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 285 or img.width > 201: output_size = (285, 201) img.thumbnail(output_size) img.save(self.image.path) img2 = Image.open(self.instructor_image.path) if img2.height > 40 or img2.width > 40: output_size = (40, 40) img2.thumbnail(output_size) img2.save(self.instructor_image.path) My settings.py: """ Django settings for Abrar_Class project. Generated by 'django-admin startproject' using Django 3.2.6. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ import os from pathlib import Path # … -
Django make the object create only once per day
Here is my Django model: class mymodel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) deleted_at = models.DateTimeField(null=True, blank=True) How can I make the object created only once per day? I know it's possible to do with unique_for_date but cannot understand how https://docs.djangoproject.com/en/4.1/ref/models/fields/#unique-for-date Also, I want to show an error if the user wanted to create more than once per day. -
WOPI issue in view and edit mode
I have implemented the wopi in my application, uploaded the new version of document while in the view mode then changed into edit mode new version of the document is not updated old version is displayed and different session is created for the same user -
Why user.has_perm print always True?
A user is assigned to a student group and from the group remove delete_permission, but the below code returns true. student_group = Group.objects.get(name='student') content_type = ContentType.objects.get_for_model(Department) department_permission = Permission.objects.filter(content_type=content_type) user = User.objects.get(email='test@gmail.com') student_group.user_set.add(user) for perm in department_permission: if perm.codename == "delete_department": student_group.permissions.remove(perm) print(user.has_perm("quiz.delete_department"), "Quiz Permission after") -
Change API_BASEURL
I'm doing a project on Django REST Framework. I need the project to run not on standard "http://127.0.0.1:8000 /", but on the server "http://localhost:8080 ". Please tell me where it needs to be corrected in my project files? -
django model AttributeError: 'str' object has no attribute 'clone'
two off my models in Django are getting the AttributeError: 'str' object has no attribute 'clone' while a run makemigration command class Statuses(models.TextChoices): publish = _('publish') archive = _('archive') draft = _('draft') category = models.ForeignKey(BlogCategory, on_delete=models.DO_NOTHING, verbose_name=_("blog category")) title = models.CharField(max_length=64, null=False, blank=False, verbose_name=_("blog title")) slug = models.SlugField(null=False, blank=False, allow_unicode=True, verbose_name=_("blog slug")) intro = models.TextField(null=False, blank=False, verbose_name=_("blog introduction")) body = models.TextField(null=False, blank=False, verbose_name=_("blog body")) created = models.TimeField(auto_now_add=True, verbose_name=_("blog creation time")) pubdate = models.TimeField(auto_now=True, verbose_name=_("blog publish time")) status = models.CharField(max_length=12, choices=Statuses.choices, verbose_name=_("blog publish status")) class Meta: ordering = ['-pubdate'] indexes = ['title'] verbose_name = _('blog') verbose_name_plural = _('blogs') and class Products(models.Model): productName = models.CharField(max_length=32, blank=False, null=False, verbose_name=_("product name")) productImage = models.ImageField(upload_to='medias/images/products/') category = models.ForeignKey(ProductCategories, on_delete=models.DO_NOTHING, verbose_name=_("product category")) weights = models.ForeignKey(Weights, on_delete=models.DO_NOTHING, verbose_name=_("product weights")) package = models.ForeignKey(Packages, on_delete=models.DO_NOTHING, verbose_name=_("product package")) class Meta: ordering = ['productName'] indexes = ['productName'] verbose_name = _('product') verbose_name_plural = _('products') and didn't find any good answer for the problem -
file.truncate doesn't clear file content
I'm using python and django for an application, and I have to stock informations in a text file. So I've done this : def write_in_file(data): stock_file = open(os.path.join(sys.path[0], "static/imported_data.txt"), "w") stock_file.truncate() stock_file.write(data) stock_file.close() It's working like I want and my file contains 'data'. But when I refresh the page, the content of the file is not cleared, and 'data' is rewrited at the end of the file. And when I print something to debug, I see that the function is called every time I refresh the page. The only time my file is properly cleared is when I modify the 'write_in_file' function. Does anyone know from where this might come from ? -
How to get pk from url in django rest framework?
I have 2 apps Ticket and Comment, with url: http://127.0.0.1:8000/api/tickets/<int:pk>/comments/<int:pk>/. comment.views class CommentAPIList(ListCreateAPIView): queryset = Comment.objects.all() serializer_class = CommentSerializer permission_classes = (IsAuthenticatedOrReadOnly,) pagination_class = CommentAPIListPagination I want to get first int:pk in my url for filter my queryset, like: queryset = Comment.objects.filter(ticket=MY_GOAL_PK) comment.models class Comment(models.Model): text = models.TextField() ticket = models.ForeignKey( Ticket, on_delete=models.CASCADE, ) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) time_create = models.DateTimeField(auto_now_add=True) time_update = models.DateTimeField(auto_now=True) def __str__(self): return self.text ticket.models class Ticket(models.Model): title = models.CharField(max_length=150) text = models.TextField() status = models.ForeignKey(Status, on_delete=models.PROTECT, default=2) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) time_create = models.DateTimeField(auto_now_add=True) time_update = models.DateTimeField(auto_now=True) def __str__(self): return self.title I don't know what other information I can give, but I can give it at your request. May be you have another solution for filtering my Comment.objects. Filtering should provide comments related only to this Ticket -
Expression expected.javascript error. The error is in the if statement and there are some errors in the terminal. Need assistance
//This is the JS Code for the Checkout page in a HTML File <script> document.getElementById('cart').innerHTML = sum; $('#itemsJson').val(JSON.stringify(cart)); //If order is placed then confirm the order with an ID {% if thank %} alert('Thanks for ordering with us. Your order id is {{id}}. Use it to track your order using our order tracker') localStorage.clear(); document.location = "/shop"; {% endif %} </script> -
Django - Can't send Whatsapp message in production mode
I am developing an app that should send msg by WhatsApp using pywhatkit. Running from Django Development Server works fine, but from Xampp it doesn't, I even tried opening whatsapp from the url directly in the project and it doesn't work either. Python 3.10.6 Django 3.2.0 def send_whatsapp(telefono, mensaje): try: pywhatkit.sendwhatmsg_instantly(telefono, mensaje, tab_close=True) print("Mensaje enviado") except Exception: print("Error") -
Order queryset based on condition from fields in different table
I have some resources that a user can subscribe to, for added advantages. My challenge is in sorting them, where the resources with subscriptions come first and the rest follow. Initially, the resources were stored like this. from django.db import models from django.utils import timezone class Entity(models.Model): has_subscription = models.BooleanField() created_at = models.DateTimeField(default=timezone.now) # other fields and I would sort them like this, Entity.objects.all()order_by("-has_subscription", "-created_at") which worked. I decided to move to a different way of storing it that would favor a time bound subscription. I came up with this. from django.db import models from django.utils import timezone class Entity(models.Model): created_at = models.DateTimeField(default=timezone.now) @property def has_active_subscription(self): if ( self.entity_subscriptions.filter( start_date__lte=timezone.now(), end_date__gte=timezone.now() ).count() > 0 ): return True return False class Subscriptions(model.Model): entity = models.ForeignKey( Entity, on_delete=models.CASCADE, related_name="entity_subscriptions", related_query_name="entity_subscription", ) start_date = models.DateTimeField() end_date = models.DateTimeField() How can I sort the queryset in such a manner that the resources with subscriptions come first. -
Django form - the same field multiple times
how can I process a form with a field: order = ModelChoiceField( required=False, queryset=OrderOd.objects.filter(Q(status='DN') | Q(status='DI')), widget=Select( attrs={ "class": "form-select form-select-md form-select-solid", "data-control": "select2", "data-multiple": "true", "multiple": "multiple", "data-placeholder": _("Vyberte objednávku ..."), "id": 'order' } ) ) In front-end, I can select multiple orders (looks like pills/tags) and in the request sent to the server it looks like this: movement: f2b7c234-fbdb-4059-bcb6-8ada46cef72c account: dbabefb7-f053-4edf-a2e3-787bf6bfc371 date: 2022-09-12 order: eb2fc726-3e97-4af2-a8b2-08f20771cfef order: 8398925b-fca6-4b25-8c48-e12940a5b5c3 order: bfa35391-5cf8-4ed8-8c44-a797da875cb4 order: 07be93ac-20b3-459c-8038-c8b023db6d66 When I inspect self.data, I got 'order': ['eb2fc726-3e97-4af2-a8b2-08f20771cfef', '8398925b-fca6-4b25-8c48-e12940a5b5c3', 'bfa35391-5cf8-4ed8-8c44-a797da875cb4', '07be93ac-20b3-459c-8038-c8b023db6d66'], but when I check the output of logger.info(self.data['order']), it gives me only the first UUID. [INFO] form.py 123: 07be93ac-20b3-459c-8038-c8b023db6d66 What I need is to access all UUIDs in the array (order) and process them instance by instance. Any idea, how to do it? Thanks -
Django: How to filter obejects in django?
I simply want to filter the most popular videos based on the views. So in the Model there is a field called views = models.IntegerField(default=0). now videos can have views like 10 42, 65, 2. So what i want to do is simply NOT filter by newest to oldest by highest number of views to the lowest number. What is the best way to achieve this? def Videos: videos = Video.objects.filter(user=channel.user, visibility="public") models.py class Video(models.Model): ... views = models.PositiveIntegerField(default=0) -
Xcode Preview not showing
I was following a YouTube tutorial about how to connect my django backend to Swift and when I finished following along, I just get a blank grey area where the phone preview should be. Anyone know why this would happen? Here's my Model file and my View. import Foundation struct Account: Codable, Hashable { var email: String var username: String var first_name: String var last_name: String var is_venue: Bool var date_joined: Date var last_login: Date var is_active: Bool var is_admin: Bool var is_superuser: Bool } And View import SwiftUI struct AccountView: View { @State var accounts = [Account]() var body: some View { ForEach(accounts, id: \.self) {item in HStack { Text(item.first_name) } }.onAppear(perform: loadAccount) } func loadAccount() { guard let url = URL(string: "http://127.0.0.1:8000/api/account/") // URL is the endpoint of API else { print("API is down") return } var request = URLRequest(url: url) request.httpMethod = "GET" request.addValue("application/json", forHTTPHeaderField: "Accept") request.addValue("Basic amZsb3JlbmNlMEBnbWFpbC5jb206QmEka2V0YmExMUZsMEppbW15ITEh", forHTTPHeaderField: "Authorization") URLSession.shared.dataTask(with: request) { data, response, error in if let data = data { if let response = try? JSONDecoder().decode([Account].self, from: data) { DispatchQueue.main.async { self.accounts = response } return } } }.resume() } } struct AccountView_Previews: PreviewProvider { static var previews: some View { AccountView() } }