Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change input method of Django default form ? from text input to choices
I have below create view, class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title','name'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) and in Post create template I just put it as a form tag <form method="POST" > {% csrf_token %} {{ form|crispy }} </form> I want name field to be dropdown choice in frontend HTML, What shall I do ? It is possible by adding choice field in models.py but I can not do that and I have another idea to implement, -
DJango Composite priamary key with instance field values
hi im having troubles in django 3.2 with a work arround for composite key's. as my customer request he needs a composite key as primary key not just on unique_together constraint so im wonder if there any way or place to intercept the instance be fore validation and populate the composite key with values from the other fields and save it to the db ej: class MyModel(models.Model): foo = models.UUIDField(default=uuid.uuid4, auto_created=True, editable=False, max_length=36) bar = models-charfield() taz = models.charfield() composite_key = models.charfield(primary_key=True, default = 'foo' + 'taz' + 'foo') somthing among these lines i cant get pass from the form field validator on django admin site so i really cant test signals or save() method any help wil be apreciated. -
how can i map manual with django-elastcisearch-dsl
So as Stack does not want i ask for clarification on it (#Near duplicate), where i have to put fields declaration under Index class or under Django class. class MyDocument(Document): class Index: # here class Django: # here Near duplicate : How to map keyword field in Django Elasticsearch? -
User has no customer
In a Django project, i have two apps; ecommerce and users. Ecommerce app has situation where logged in users are expected to be customers and they can add to cart. Non logged in users can as well add to cart. In the users app, new users are to register, logged in and be redirected to the store page(store.html). The new registered users does not have this customer instance I guess, reason I'm getting the User has no customer RelatedObjectDoesNotExist. How can I integrate this new registered users to have this customer instance so they can be redirected to the store page? or give a condition where not all users must have a customer instance. (ecommerce app) models.py: class Customer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200) def __str__(self): """String for representing a model object""" return self.name class Product(models.Model): name = models.CharField(max_length=200) price = models.DecimalField(max_digits=7, decimal_places=2) digital = models.BooleanField(default=False,null=True, blank=True) image = models.ImageField(null=True, blank=True) def __str__(self): """String for representing a model object""" return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=True) transaction_id = … -
Blog matching query does not exist
I am using slug to to show my blog details page. here is models.py class Blog(models.Model): author=models.ForeignKey(User,on_delete=models.CASCADE,related_name='post_author') blog_title=models.CharField(max_length=264,verbose_name='Put a Title') slug= models.SlugField(max_length=264,unique=True) blog_content=models.TextField(verbose_name='what is on your mind?') blog_image=models.ImageField(upload_to='blog_images',verbose_name='Image') publish_date=models.DateTimeField(auto_now_add=True) update_date=models.DateTimeField(auto_now=True) class Meta: ordering = ('-publish_date',) def __str__(self): return self.blog_title+' From :'+str(self.author) blog list views.py def Creating_blog(request): form=BlogForm() if User.is_authenticated: if request.method=='POST': form=BlogForm(request.POST,request.FILES) blog_obj=form.save(commit=False) blog_obj.author=request.user title=blog_obj.blog_title blog_obj.slug = title.replace(' ','-') + '-'+ str(uuid.uuid4()) blog_obj.save() return redirect('bloglist') return render(request,'blogs/createblog.html',{'form':form}) urls.py from django.urls import path from .import views urlpatterns = [ path('write/',views.Creating_blog,name='creatingblogs'), path('bloglist/',views.BlogList.as_view(),name='bloglist'), path('details/<slug:slug>/',views.blog_details,name="blog_details") ] blog_list page html anchor tag code <div class="col-sm-8"> <p>{{blog.blog_content|capfirst|truncatewords:100}}<a href="{% url 'blog_details' slug=blog.slug|slugify %}">Read More</a></p> </div> I can see the blog list page but when it try to see blog details it shows me this error DoesNotExist at /details/big-time-space-rarity-9a3d63b4-634a-11ec-9db9-9c7bef6a0e62/ Blog matching query does not exist. I have tried adding some new blog but it shows me the same. please help me out this and kindly ask me if any description needed. Thanks in advance. -
How to reference a index field from fk model in admin
I want to made a thumbnail in admin model. For now i have: models.py class ProductImages(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image_type = models.CharField(max_length=33,default='image_type') image_file = models.ImageField( upload_to='images/', null=True, blank=True, default='magickhat-profile.jpg' ) admin.py class AdminProductModel(admin.ModelAdmin): model = Product def product_thumb(self, obj): # return HTML link that will not be escaped return mark_safe( '<img src="%s" style="width:30px;height:30px;">' % (ProductImages.image_file.url)"""here is my doubt, i need only 1 image""" ) list_display = ['product_thumb','user','slug','created_at'] ... Well, the ProductImages model store all images related with Product model, and i need get 1 image related to made thumbinail in admin -
Access denied to css file that is public on S3 AWS bucket
So I have a Django application running on a docker container, on AWS EC2. The static content is hosted on an S3 bucket (css, javascript, etc.). This all works fine. I did implement a PDF output for some files using weasy print. Locally, it produces the expected PDF fine. However on the server, I get a 500 error. Upon closer inspection, the following error popped in the django logs that I have added to my decorator (that is responsible for generating the PDF). The decorator decorates some handle that is called, and the produced PDF shows up in the download folder. A decorated handler: @generate_pdf_httpresponse def handler_warehouse_packingslip(request, **kwargs): id = kwargs.get("pk") context = { .... details to provide to print.... } filename = "foo.pdf" infos = {"context":context, "template_path":'projectlibs/pdf_outputs/pdf_base.html', "extra_css_files":[], "filename":filename,"request":request} return infos The decorator: def generate_pdf_httpresponse(func): @functools.wraps(func) def wrapper_generate_pdf_httpresponse(*args, **kwargs): try: logger.info(f"Wrapper for pdf response") value = func(*args, **kwargs) html_string = render_to_string(value.get("template_path"), context=value["context"]) html = HTML(string=html_string, base_url=value["request"].build_absolute_uri()) css_files = [] pdf = html.write_pdf(stylesheets=css_files) logger.info(f"Creating tmp file for pdf response") with tempfile.NamedTemporaryFile() as file: file.write(pdf) file.seek(0) stream = file.read() httpresponse = HttpResponse(content_type='application/pdf;', content=stream) httpresponse['Content-Disposition'] = f'attachment; filename={value["filename"]}' httpresponse['Content-Transfer-Encoding'] = 'binary' return httpresponse except Exception as ex: logger.error(f"PDF wrapper failed: {ex}") return … -
Django: Filtering the fields of the m2m model from the models associated with the m2m model will take time
There are quite a few lines of code and logs that may be complicated and difficult to understand. I apologize for that. The following is OR full-text search for Video.title and Tag.name using pgroonga, an extension for full-text search. But the query takes about 2000-4000 ms to execute. The number of hits is about 130,000, but we have a LIMIT 20 limit. The index for full-text search is being used successfully. Video: 300K rows Tag: 5K rows video_tag_through: 1.3M rows # models.py class Tag(models.Model): name = models.CharField(unique=True, max_length=30) created_at = models.DateTimeField(default=timezone.now) ... class Video(models.Model): title = models.CharField(max_length=300) tags = models.ManyToManyField(Tag, blank=True) updated_at = models.DateTimeField(auto_now=True) ... class History(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) video = models.ForeignKey(Video, on_delete=models.CASCADE) ... class Favorite(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE video = models.ForeignKey(Video, on_delete=models.CASCADE) ... class Playlist(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) is_wl = models.BooleanField(default=False, editable=False) ... class Track(models.Model): playlist = models.ForeignKey(Playlist, on_delete=models.CASCADE, null=True) video = models.ForeignKey(Video, on_delete=models.CASCADE) ... # migration file ... operations = [ migrations.RunSQL( "CREATE EXTENSION pgroonga", "DROP EXTENSION pgroonga", ), migrations.RunSQL( "CREATE INDEX pgroonga_video_index ON videos_video USING pgroonga (title pgroonga_varchar_full_text_search_ops_v2)", "DROP INDEX pgroonga_video_index", ), migrations.RunSQL( "CREATE INDEX pgroonga_tag_index ON videos_tag USING pgroonga (name pgroonga_varchar_full_text_search_ops_v2)", "DROP INDEX pgroonga_tag_index", ), ] # lookups.py class Groonga(Lookup): lookup_name = … -
Create list of Approvers Django
I am trying to create an application where you can create project-based expenses, and each project should have a list of approvers who will approve the expense once uploaded to the project, how do I replicate this in Django. What I tried to do. I got the approvers into the form as a ModelMultipleChoiceField self.fields['approvers'] = forms.ModelMultipleChoiceField(queryset=Profile.objects.all()) and saved it as a list into the database def getApprovers(approvers): id = [] for profile in approvers: id.append(profile.id) return id in project create function project.approvers = getApprovers(form.cleaned_data['approvers']) I created a templatetag to display the list of approvers as the Profile Queryset objects. I tried to iterate over the saved list of approvers, but I keep getting errors def approvers_list(approvers): for profile in list(approvers): return profile How better can I represent this. here is the project and expense models class Project(MiscClass): owner = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True, blank=True) organisation = models.ForeignKey(Organisation, on_delete=models.SET_NULL, null=True, blank=True) title = models.CharField(max_length=200, null=True, blank=True, unique=True) slug = models.SlugField(max_length=500, null=True, blank=True, unique=True) category = models.ForeignKey('Category', on_delete=models.CASCADE, null=True, blank=True) description = models.TextField(null=True, blank=True) approvers = models.CharField(max_length=100, null=True, blank=True, validators=[int_list_validator]) class Meta: ordering = ['-created'] def __str__(self): return str(self.title) def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Project, self).save(*args, **kwargs) class Expense(MiscClass): PROCESSING … -
ModuleNotFoundError: No module named 'PIL' , after installing in new PC
I have cloned a Git repo which have Pillow==5.2.0,but even after installing it results in above error during execution. Currently the models.py have, from PIL import Image Tried, import Image from Pillow import Image import Image // after installing Image library but no success, However the same Git repo works perfectly on Win 7 machine but after cloning and installing in new Win 10 , the error happens Project link https://github.com/Anoop-George/farmproject.git -
Name is not defined (Django queryset.filter) [closed]
What i want to do is i want to only show article comments that belongs to article that author has a public profile attribute. Here is the problem ,i get "name is not defined" on filters which points to here: Filters #this works totally fine class FollowedUserServiceCommentFilterBackend(filters.BaseFilterBackend): def filter_queryset(self, request, queryset, view): return queryset.filter( userservice__author__followers__author=request.user ) #this is the one with issue class PublicUserServiceCommentFilterBackend(filters.BaseFilterBackend): def filter_queryset(self, request, queryset, view): return queryset.filter( userservice__author__public_profile = true ) But the interesting thing is that i have another filter which works pretty fine (as i pointed above). Views.py class PublicUserServiceCommentViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = UserServiceComment.objects.all() serializer_class = UserServiceCommentSerializer filter_backends = [PublicUserServiceCommentFilterBackend] Models class UserServiceComment(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='userservicecomments_set') userservice = models.ForeignKey(UserService, on_delete=models.CASCADE, related_name='userservicecomments') content = models.CharField(max_length=100) class UserService(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE,null=True,related_name='userservices') userservice = models.CharField(unique=False,max_length=100,null=True,blank=True) class User(AbstractUser,PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.CharField(max_length=255,unique=True) public_profile = models.BooleanField(default=True) I get "name not defined" but i can't point out which name it is. When i try directly from browser it is fine but it gives error when trying from Curl or Json. Syntax looks fine, I checked it multiple times. What is the issue?Did I … -
127.0.0.1:8000/admin/ won't load up
Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 4.0 Exception Type: TypeError Exception Value: 'set' object is not reversible Exception Location: C:\Users\User\PycharmProjects\pythonProject2\venv\lib\site-packages\django\urls\resolvers.py, line 494, in _populate Python Executable: C:\Users\User\PycharmProjects\pythonProject2\venv\Scripts\python.exe Python Version: 3.10.0 Python Path: ['C:\Users\User\PycharmProjects\pythonProject2\mywebsite', 'C:\Users\User\AppData\Local\Programs\Python\Python310\python310.zip', 'C:\Users\User\AppData\Local\Programs\Python\Python310\DLLs', 'C:\Users\User\AppData\Local\Programs\Python\Python310\lib', 'C:\Users\User\AppData\Local\Programs\Python\Python310', 'C:\Users\User\PycharmProjects\pythonProject2\venv', 'C:\Users\User\PycharmProjects\pythonProject2\venv\lib\site-packages'] Server time: Mon, 27 Dec 2021 18:46:36 +0000 -
Django Admin panel refuses Content Security Policy
I am struggling to use django-csp in my admin panel, I can see my frontend with vue3 and vite, you can see my demo site on here. When I try to log in admin I get a black screen and in the console, I see the error below: Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' fonts.googleapis.com ajax.cloudflare.com static.cloudflareinsights.com www.google-analytics.com ssl.google-analytics.com cdn.ampproject.org www.googletagservices.com pagead2.googlesyndication.com". Either the 'unsafe-inline' keyword, a hash ('sha256-Tq5HCCxkFfCSF4NPeTUcXBhJqVIuv2SvsJXpa2ACR2Y='), or a nonce ('nonce-...') is required to enable inline execution. I configured my django-csp in my settings: # default source as self CSP_DEFAULT_SRC = ("'none'",) CSP_INCLUDE_NONCE_IN = ["default-src"] CSP_STYLE_SRC = ("'self'", 'fonts.googleapis.com', "'unsafe-inline'", "'unsafe-eval'", "https") # scripts from our domain and other domains CSP_SCRIPT_SRC = ("'self'", 'fonts.googleapis.com', "ajax.cloudflare.com", "static.cloudflareinsights.com", "www.google-analytics.com", "ssl.google-analytics.com", "cdn.ampproject.org", "www.googletagservices.com", "pagead2.googlesyndication.com") # images from our domain and other domains CSP_IMG_SRC = ("'self'", "www.google-analytics.com", "raw.githubusercontent.com", "googleads.g.doubleclick.net", "mdbootstrap.com") # loading manifest, workers, frames, etc CSP_FONT_SRC = ("'self'", 'fonts.gstatic.com', 'fonts.googleapis.com') Can you help me to fix this? Thanks -
Django - how to validate data from post that is not in a django form?
I am receiving post data from my template but it's being created with js, it is not a django form. I know that if I am posting a field using a django form I can use form.is_valid() or x = form.cleaned_data['field'] but I don't know how to validate/clean my data when not using a django form. The reason that I'm using js for this form/template is to get a specific look that I couldn't do with a standard django template/form. models.py class AssessComment(models.Model): assessment = models.ForeignKey(Assessment, on_delete=models.CASCADE) student = models.ForeignKey(Student, on_delete=models.CASCADE) comment = models.TextField(blank=True) js snippet // this js is appended to the grade-form element in the template document.getElementById('grade-form').appendChild(table); comment = document.createElement('td'); commentName = "row-" + n + "-comment"; commentText = document.createElement("textarea"); commentText.setAttribute("name", commentName); rowName[n].appendChild(comment); comment.appendChild(commentText); The above js is putting a textarea in a table and giving it the name commentName. The template sends this as a post to my view. I iterate through several rows of n. template div class="form-group"> <form action="" method="post">{% csrf_token %} <div id="grade-form"></div> <!-- js is inserted here --> <div class="form-group"> <button type="submit" class="btn btn-primary">Submit</button> </div> </form> </div> views.py while s < len(cs): comment = "row-" + str(s) + "-comment" form_comment = request.POST[comment] # … -
Django This backend doesn't support absolute paths after integrating aws S3 bucket
I found similar question on stackoverflow on this topic but still now my problems didn't solved. I am facing following problems after integrating aws S3 bucket: problem 1: Image resizing not working after integrating aws S3 bucket. problem 2: getting this error page after image upload NotImplementedError at /blog/edit/hello/ This backend doesn't support absolute paths. here error details of my terminal "C:\Users\Fdg\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\files\storage.py", line 123, in path raise NotImplementedError("This backend doesn't support absolute paths.") NotImplementedError: This backend doesn't support absolute paths. [27/Dec/2021 23:49:44] "POST /blog/edit/hello/ HTTP/1.1" 500 118419 my settings.py AWS_ACCESS_KEY_ID = "my acess key" AWS_SECRET_ACCESS_KEY = "my secret key" AWS_STORAGE_BUCKET_NAME = "my bucket name" AWS_S3_CUSTOM_DOMAIN = 'my aws domain name' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} AWS_DEFAULT_ACL = 'public-read' AWS_S3_FILE_OVERWRITE = False AWS_QUERYSTRING_AUTH = False DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_MEDIA = '/media/' AWS_STATIC = 'static' STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_STATIC) MEDIA_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_MEDIA) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' here is my models.py for upload images: class BlogHeaderImage(models.Model): image = models.ImageField(upload_to='blog/images/',validators=[validate_file_size,FileExtensionValidator( ['png','jpg'] )]) blog = models.ForeignKey(Blog,on_delete=models.CASCADE,related_name="blog_header_image") def save(self,*args,**kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: out_put_size = (300,300) img.thumbnail(out_put_size) img.save(self.image.path) def __str__(self): return str(self.blog) Though I am getting this error but image is uploading on aws … -
Django get count of total quantity in cart
I 'm trying to get the total quantity of the items I have added to cart. e.g. Item id 1 quantity 1 pc Item id 2 quantity 1 pc Item id 3 quantity 4 pcs There are 6 pcs in total in cart. In cart detail page, I could get correct count using this line {{cart.get_total_qty}} This is my cart.py page: class Cart(object): def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self, product, quantity=1, update_quantity=False): product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} if update_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def save(self): self.session[settings.CART_SESSION_ID] = self.cart self.session.modified = True def remove(self, product): product_id = str(product.id) if product_id in self.cart: del self.cart[product_id] self.save() def __iter__(self): product_ids = self.cart.keys() products = Product.objects.filter(id__in=product_ids) for product in products: self.cart[str(product.id)]['product'] = product for item in self.cart.values(): item['price'] = Decimal(item['price']) item['total_price'] = item['price'] * item['quantity'] item['quantity'] = int(item['quantity']) yield item def __len__(self): return sum(item['quantity'] for item in self.cart.values()) def get_total_price(self): return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values()) def get_total_qty(self): return sum(item['quantity'] for item in self.cart.values()) def clear(self): del self.session[settings.CART_SESSION_ID] self.session.modified = True Now I … -
Getting errors after installing Django AllAuth and migrating
Help! I'm getting errors after installing Django AllAuth and migrating! Errors: File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/opt/virtualenvs/python3/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute django.setup() File "/opt/virtualenvs/python3/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/django/apps/registry.py", line 93, in populate raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: auth``` -
Какие поля нужны для хранения счета? [closed]
Нужна модель матча по пинг понгу. Требуется модель, из которой можно будет взять следующие данные: Время | Игрок1 | Игрок2 | Выигранные сеты игрока1 | сеты игрока2 | счет по сетам например 16.01.01 | олег | данил | 3 | 0 | 11:3, 11: 6, 11: 9 пока что модель выглядит так class Game(models.Model): date = models.DateTimeField(auto_now_add=True) player1 = models.CharField() player2 = models.CharField() sets1 = models.IntegerField() sets2 = models.IntegerField() А какие поля нужны для хранения счета? Еще важно, что количество сетов может быть разным, и соответственно количество счетов по сетам тоже. -
How can I limit access to certain urls depending on the logged in user?
first of all I want to clarify that I am new to this, so if I fail in some concepts I apologize in advance. I have configured the django administration panel, with an administrator user and two other users that I need to have different permissions to access certain urls of the web environment. In the home page there are three titles with links to three different sections of the page: SECTION A, SECTION B AND SECTION C. I want to have a user that has access to all the sections of the page and the other user that has access only to two sections. How can I manage that? Another thing I would need is the following: in my configuration, by default, when you launch the web server, the first thing that opens is the django administration portal, but I need that when you log in with a user, access directly to the url that has permissions. Thanks in advance -
Understand the responsibility of each part of django architecture
Im a little confuse about Django responsibility architecture. In my project, i chose work with CBV and built-in urls. In my studies, i understood that the responsibilities are divided into: Model, View, Template where: Model takes care data and DataBase, from docs : "definitive source of information about your data. It contains the essential fields and behaviors of the data you’re storing" View takes care about request and response Template is a hight level layer app to show data correct me if not that. Most of my questions are where to put the codes, eg: In my models i use something like: class Product(models.Model): ..."""other fields""" user = models.ForeignKey(User, on_delete=models.CASCADE) product_title = models.CharField(max_length=255, default='product_title') product_title_seo = models.CharField(max_length=255, default='product_title_seo') slug = models.SlugField(max_length=250,unique=True,null=True) def __str__(self): return self.product_title def get_absolute_url(self): return reverse('product_change', kwargs={'slug': self.slug, 'pk': self.pk}) def save(self, *args, **kwargs): self.product_title_seo = slugify(self.product_goal + " " + self.product_type + " " + self.product_district) self.product_title = slugify(self.product_title) if not self.slug: self.slug = self.product_title_seo return super().save(*args, **kwargs) So as we can see i have 3 methods inside my model class, but i need some treatment for the majority of fields which would represent a considerable increase in methods. This approach is correct, a lot of … -
Is there any specific condition, When to use APIView and when to use ViewSets in Django
IN Serialezers.py file I have seen, that the user is using APIView in one and Modelviewset in few. from django.shortcuts import render from rest_framework import serializers from rest_framework.response import Response from rest_framework.utils import serializer_helpers from rest_framework.views import APIView from rest_framework.viewsets import ModelViewSet from .models import * from rest_framework import status from .serializers import * class ProductList(APIView): def get(self, request): products = Product.objects.all() serializer = ProductSerializer(products, many=True) return Response(serializer.data) def post(self, request): serializer = ProductSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class CategoryViewSet(ModelViewSet): serialzer_class = CategorySerializer queryset = Category.objects.all() -
Rounding up a decimal not working properly in python(or django)
I was trying to round up a decimal with the code I found below, but it doesn't seem to work properly in python(django). Here is the code: import math def round_up(n, decimals=0): multiplier = 10 ** decimals return math.ceil(n * multiplier) / multiplier Here are some of the results I get when I run the function: print(round_up(20.232, 2)) print(round_up(20.0, 2)) print(round_up(20.4, 2)) 20.24 20.0 20.4 However, for some reason, I get a weird value when I input 80.4. I am getting 80.41 instead of 80.4: print(round_up(80.4, 2)) 80.41 Is there any other way I can round up decimals in python(django)? I have gotten this off the internet, so there might be some other problems other than the one I mentioned above(inputting 80.4). Basically, I just want to round up a decimal to the second decimal point like above(but of course rounding up 80.4 or 20.3 would just be 80.4 and 20.3 respectively). Thank you, and please leave any questions you have. -
How to send file from system storage django?
I want to send file from my FileSystemStorage as response of a POST request, but every time i getting my error handler triggered. Why? def get_frame(request): frame_number = request.POST['frame_number'] filename = request.POST['filename'] fss = FileSystemStorage() # creating name of file i need name = f'frame_{frame_number}_{filename.replace(".mp4", "")}.png' # execute file path img = fss.path(name) return FileResponse(open(img, 'rb')) script.js for(let i=0; i<=frames_needed; i++) { let frame_number = fps * i // making POST request for 1 frame let img = get_each_frame(frame_number, filename) img.done(function(response) { console.log(response) }) // getting this handler triggered img.fail(function(error) { console.log(error, 'error') }) } get_each_frame function function get_each_frame(frame_number, filename) { let request = $.ajax({ type: "POST", url: "get_frame", data: { 'frame_number': frame_number, 'filename': filename, 'csrfmiddlewaretoken': $('[name=csrfmiddlewaretoken]').val(), }, dataType: "json", }); return request } -
Django Models return fileds as columns for django admin
I looked a lot but I couldn't find a way to return my model to django admin with the columns not only the model name: What I wish to accomplish from my model is to have the fields represent as columns in django admin, such as it is in users: I have a model called Products: from django.db import models # Create your models here. class Product(models.Model): title = models.CharField(max_length=30, null=False, blank=False) price = models.FloatField(null=False, blank=False) description = models.CharField(max_length=250, null=False, blank=False) longDescription = models.TextField(max_length=900, null=True, blank=True) def __str__(self): return self.title It's register on admin site so I can see it as: I'm looking for a way to have my products listed as users, with the id, price, description as columns... Is it possible? Thanks in advance! -
get_extra_restriction() missing 1 required positional argument: 'related_alias' error django
I deployed my django site on heroku and when i run my url which uses django taggit in it error shows up. I am using django taggit for meta keys to find related blogs.