Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django use external postgresql database including File fields
I have a Django app and I need to separate the database (PostgreSQL) and put it in another server. My question is about file fields. I have some file fields in model and it includs models.FileField(upload_to='media/'). Do files automatically upload to database server or not? thanks -
django context processor not returning result
I have a simple django application with a shopping cart app and a main app to display items for sale. I have added a context processor to show the contents of the cart on each page. This seems simple enough, but I am getting no results and I can not figure out why. Relevant section of my settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.i18n', 'django.contrib.messages.context_processors.messages', 'asdf_cart.context_processors.cart', ], }, }, ] My context_processors.py from my asdf_cart app: from .cart import Cart def cart(request): return {'cart': Cart(request)} And a section from my views.py from my asdf_cart app: def cart_detail(request): cart = Cart(request) context = {} context['key'] = settings.STRIPE_PUBLISHABLE_KEY for item in cart: item['update_quantity_form'] = CartAddProductForm(initial={'quantity': item['quantity'], 'update': True}) return render(request, 'asdf_cart/cart.html', {'cart': cart, 'context': context}) A selection from my cart.py from my asdf_cart app: def get_total_price(self): return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values()) This works fine on my cart page in my asdf_cart app. No issue, everything is displayed as it should be. Howver, when trying to get total price from my cart using the context_processor from a page in my main app, I get nothing. … -
Django REST Framework - let ListAPIView behave similar to pure ListView
I am trying to convince ListAPIView to behave the way the ListView from pure Django does (that means, renders a template with an object_list variable, possibly some pagination stuff, and so on). This is what I tried: class UserListView(ListAPIView): permission_classes = (AllowAny, ) queryset = User.objects.all() serializer_class = UserListSerializer renderer_classes = (TemplateHTMLRenderer, ) template_name = 'user/list.html' Assume the User to be the builtin Django user model, UserListSerializer to be a ModelSerializer with fields = "__all__" and the template containing just a for loop over object_list displaying all the users. When I try it, I get the following error: TypeError: context must be a dict rather than ReturnList. I must be doing something terribly wrong, I believe there must me a way to make use of the genericity and I just have no idea how. -
How to save user input img in ImageField in Django
I am try to save user image in my database if my input form is this form : <form method="POST" action="/savedata/"> {% csrf_token %} <input id="file-upload" type="file" accept="image/*" name='profileimg' /> <input type="submit" value="upload"> </form> how can i save this input select image on database using form submit this is my model class model: class usertab(models.Model): img = models.ImageField(upload_to='user_img') i am able to save image using superuser but i need to save this using form submition how i can do that please tell me -
Choosing right tech stack for a highly secure payments web application?
Idea is to have a highly scalable and highly secure web app. Now I am used to building web application(with Django rest framework backend and react frontend), but I'm not sure about security this way. I have multiple questions: What should I use for backend system ? (In terms of Languages I know python and JS)? Should I build a complete server side web app? How do I achieve maximum security with less effort? Thanks a lot for the advice. -
Django issue with static css files
I have an issue with Django static files. With Javascript files work successfully. Helps please. Django console static error Django CSS FILE Declarations Browser error -
Django queryset for Status field
i have a status field at my model "CategoryRequests" that can have Waiting, Accepted, Rejected. How can i filter for the status? I only want to filter for "Waiting" and order by "-pk" so how do i combine these two, e.g.: list_requests = CategoryRequests.objects.filter(status='Waiting') list_requests = CategoryRequests.objects.get_queryset().order_by('-pk') Thanks and BR -
React: You may need an appropriate loader to handle this file type
I am a newbie when it comes to react and webpack4 and doesn't have much experience with Javascript either. I get the follwing error when I run npm run dev (see package.json further down): ERROR in ./project/frontend/src/components/App.js 6:2 Module parse failed: Unexpected token (6:2) You may need an appropriate loader to handle this file type. | import Table from "./Table"; | const App = () => ( > <DataProvider endpoint="api/lead/" render={data => <Table data={data} />} /> | ); | const wrapper = document.getElementById("app"); @ ./project/frontend/src/index.js 1:0-35 Package.json looks like this: { "name": "django-drf-react-quickstart", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev": "webpack --mode development ./project/frontend/src/index.js --output ./project/frontend/static/frontend/main.js", "build": "webpack --mode production ./project/frontend/src/index.js --output ./project/frontend/static/frontend/main.js" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "@babel/core": "^7.3.3", "@babel/preset-env": "^7.3.1", "@babel/preset-react": "^7.0.0", "babel-loader": "^8.0.5", "babel-plugin-transform-class-properties": "^6.24.1", "prop-types": "^15.7.2", "react": "^16.8.2", "react-dom": "^16.8.2", "weak-key": "^1.0.1", "webpack": "^4.29.4", "webpack-cli": "^3.2.3" } } .babelrc: { "presets": [ "@babel/preset-env", "@babel/preset-react" ], "plugins": [ "transform-class-properties" ] } I'm following this tutorial: https://www.valentinog.com/blog/tutorial-api-django-rest-react/#Django_REST_with_React_requirements. -
while checking the command pip freeze, the segmentation fault error is showing
I am trying to install a virtual env. for python django. when I try pip freeze to check django version it says "segmentation fault core dumped" while using pip install django command its giving the same error -
Get user username and uuid
i have a question how i can get username and uuid in template Views join_count = list(Profile.objects.all().aggregate(Max('join_count')).values())[0] Model user = models.OneToOneField(User, on_delete=models.CASCADE) How to enable access to uuid and username via join_count -
Django: Filtering many to many field with whole same queryset?
With the following models: class OrderOperation(models.Model): ordered_articles = models.ManyToManyField(Article, through='orders.OrderedArticle') class OrderedArticle(models.Model): order_operation = models.ForeignKey(OrderOperation) article = models.ForeignKey(Article) articles = ... # some queryset containing multiple articles If I want to find order operations containing at least one article, this works as expected: OrderOperation.objects.filter(ordered_articles__in=articles) However, if I want to find order operations with all the articles in the order, what is the correct way to do it? OrderOperation.objects.filter(ordered_articles=articles) raises a ProgrammingError: more than one row returned by a subquery used as an expression error (I understand why actually). -
i have this probleme with python and django urls.py
I created a virtual environment for python on vscode and I have a problem on the file urls.py which displays problems on two lines help me please enter image description here -
Django TestCase class - why are some methods camel case and others snake case?
https://docs.djangoproject.com/en/2.1/_modules/django/test/testcases/#TestCase.setUpTestData As far as I know, the convention is to use snake case for method names, so why do we see some methods in camel case in Python? -
Template tag to check if file exists not working when used with thumbnail package in django
I have a django site that displays data imported from an API, thousands of records. Part of the data that is obtained via API is an image path, and I have checks to see if the image is valid (i.e. no 404 error when attempting to retrieve) before putting into my local database. This is to ensure my thumbnail package doesn't encounter an image path for which there is no image, as that throws an error in my application (and I have yet to put in exceptions to deal with that). Recently, for one of the categories for which we pull data from the API, someone made a mistake, and instead of an image path giving a 404 error if it doesn't exist, it redirects back to the homepage, which doesn't result in an error, and indeed results in a valid entry in my local database without a corresponding image file to match. I am using a custom template tag to check if a file exists, and if not to display a different image. The template tag is: from django import template from django.core.files.storage import default_storage register = template.Library() @register.filter(name='file_exists') def file_exists(filepath): if default_storage.exists(filepath): return filepath else: new_filepath = 'images/default.jpg' … -
Bootstrap4 in Django not working as intended
This is a picture --> http://prntscr.com/mp0lj8 After that world image i have empty white space..I dont know what is the problem. Can any Django user tell me were i went wrong This is html code in base template with load static and {% block content %} inside of it {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'seo_marketing/main.css' %}">> {% if title %} <title>Web Marketing Site - {{ title }}</title> {% else %} <title>Home Page</title> {% endif %} </head> <body id="body"> <header class="site-header"> <nav class="navbar navbar-expand-md navbar-light bg-steel fixed-top"> <div class="w-75 container-fluid"> <a class="logo nav-link" href="{% url 'index-page' %}">Web Marketing Services</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarToggle"> <div class="navbar-nav mr-auto"> </div> <!-- Navbar Right Side --> <div class="navbar-nav"> <a class="nav-item nav-link" style="color:#f3f3f3;" href="{% url 'index-page' %}">Home</a> <a class="nav-item nav-link" style="color:#f3f3f3;" href="#">About Us</a> <a class="nav-item nav-link" style="color:#f3f3f3;" href="#">Services</a> <a class="nav-item nav-link" style="color:#f3f3f3;" href="#">Portfolio</a> <a class="nav-item nav-link" style="color:#f3f3f3;" href="#">Blog</a> <a class="nav-item nav-link" style="color:#f3f3f3;" href="#">Contact</a> </div> </div> </div> </nav> </header> <div class="container-fluid"> {% block content %}{% endblock %} </div> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> … -
DRF - CreateAPIView Nested Serializer
I've an interesting question and want expert views on it. I've the following models. class A(models.Model): b = ForeignKey(B) c = ForeignKey(B) d = ForeignKey(B) class B(models.Model): pass class C(models.Model): pass class D(models.Model): pass Following are my serializers: class ASearializer(serializers.Serializer): b = BSearializer() c = CSearializer() d = DSearializer() class Meta: model = A fields = ('b', 'c', 'd') def create(self, data): # I create the instance of A, B, C and D. return instance_of_A class BSearializer(serializers.Serializer): class Meta: model = B fields = '__all__' class CSearializer(serializers.Serializer): class Meta: model = C fields = '__all__' class DSearializer(serializers.Serializer): class Meta: model = D fields = '__all__' My views:- class View(CreateAPIView): serializer_class = Aserializer queryset = A.object.all().select_related('b').select_related('c').select_related('d') Everything works as expected. The request and the response works correctly. However, the queries fired are not the way it was expected. While returning the data, DRF fires 3 extra queries to filter B, C and D, thereby ignoring the queryset. 1) What is the purpose of queryset when in case of CreateAPIView? 2) How to make DRF fire one single JOIN query? -
generate random value form other field value in Django
I have a booking system for bank line : this is my model for the customer: class Customer(models.Model): customer_bank = models.ForeignKey('Bank', on_delete=models.SET_NULL,related_name='coustmer_bank' ,null=True) customer_branch = models.ForeignKey('Branch', on_delete=models.SET_NULL,related_name='coustmer_branch',null=True) booking_id = models.CharField(max_length=120, blank= True,default=increment_booking_number) identity_type = models.ForeignKey('IdentityType',on_delete=models.SET_NULL,related_name='identity_type',null=True) identity_or_passport_number = models.CharField(max_length=20) bank_account_no = models.CharField(max_length=15) Done = models.BooleanField(default=False) booking_date_time = models.DateTimeField(auto_now_add=True, auto_now=False) Entrance_date_time = models.DateTimeField(auto_now_add=False, auto_now=True)# Must be modified to work with Entrance Date and Time def __str__(self): return self.booking_id I need to generate random depends on bank_number and the branch_number and the Customer id so how can I do that? help please -
Why APIClient return empty data response Django RF
I'm traying to make some tests for an api here is the code: tests.py def test_get_lists(self): response = self.api_client.get('/api/t/') print(response.data) self.assertEqual(response.status_code,status.HTTP_200_OK) viewset.py class TableViewset(ModelViewSet): queryset = Table.objects.all() serializer_class = TableSerializer serializers.py class TableSerializer(serializers.ModelSerializer): lists = ListSerializer(many=True, read_only=True, required=False) class Meta: model = Table fields = ('id', 'user', 'title', 'id', 'timestamp', 'lists') def create(self, validated_data): table = Table.objects.create(**validated_data) return table def update(self, instance, validated_data): instance.title = validated_data.get('title', instance.title) return instance when I want to print the response data in test.py, I get an empty array. -
How to specify image specs in Django imagekit outside the field definition?
I have the following model definition: class Photo(models.Model) : def get_gallery_path(self, filename): ext = filename.split('.')[-1] filename = "%s.%s" % (uuid.uuid4(), ext) return 'static/uploads/images/gallery/' + filename uploader = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(default=date.today) image = ProcessedImageField(default='', verbose_name='Image', upload_to=get_gallery_path, processors=[ResizeToFill(100, 50)], format='JPEG', options={'quality': 60}) caption = models.CharField(max_length=200, null=True, blank=True) def __str__(self): return str(self.id) + str(self.uploader.username) + str(self.date) class Meta: verbose_name_plural = "Photos" verbose_name = "Photo" I have used django-imagekit to modify the uploaded images. But as you can see, I have to state all the properties and options inline in the image field. This makes the code hard to read when I specify many properties. Is there a way to define the properties and options separately in the models.py file such that I can use it for all my image fields. -
Django clean_FIELDNAME() not called
My custom validation method is not working and to make sure that it is even called I added sys.exit() to it. The forms completes the saving with the error and ignored the method and it is even not called as the exit() has no effect: from django.conf import settings from django import forms class Category(MPTTModel): class Meta: verbose_name_plural = "Categories" name = models.CharField(max_length=100) def clean_name(self): import sys sys.exit() name = self.cleaned_data["name"] if settings.PK_PLACEHOLDER in name: raise forms.ValidationError(f"{settings.PK_PLACEHOLDER} " "is a reserved placeholder!") return name Why is that? -
Django upload_to by 'username'
I want to upload file by username. class Beat(models.Model): title = models.CharField(max_length=100, blank=True, default='') author = models.CharField(max_length=100, blank=True, default='') owner = models.ForeignKey(User, related_name='beats', on_delete=models.CASCADE, default='', blank=True, null=True) mbeat = models.FileField(upload_to='beat/', default = 'static/None/No-beat.mp3') This is my abstract code. This code uploads a file to 'beat' folder. However, I want to make the storage more effective in visibility. I tried to add author name to upload_to parameter like this: upload_to='beat/%s/' %author but this didn't make it. How can I solve this problem? Thanks. -
Django Create new model instance from object
my site uses a rating feature where users are able to create a request for a new category, afterwards at least 100 users have to rate on this request, if 100/100 users have rated positiv for this request, the category should get created but i don't know how i can create the category model instance after the rating has reached 100/100 Positive votes. views.py def category_request_up_vote (request, pk): category_request = get_object_or_404(CategoryRequests, pk=pk) try: if request.method == 'GET': if category_request.author == request.user: messages.error(request, 'You are trying to vote a request you created by your own. Thats not possible (Transmision ignored).') return redirect('category_request_detail', pk=category_request.pk) if CategoryRequests_Vote.objects.filter(voter=request.user, voted=category_request).exists(): messages.error(request, 'You already Voted this request. Double votes are not allowed (Transmision ignored).') return redirect('category_request_detail', pk=category_request.pk) else: if category_request == 100: print("So what should i do now?") else: category_request.up_vote = F('up_vote') + 1 category_request.save() CategoryRequests_Vote.objects.create(voter=request.user, voted=category_request) messages.success(request, 'You have successfully Provided an Up-Vote for this Request.') return redirect('category_request_detail', pk=category_request.pk) else: messages.error(request, 'Uuups, something went wrong, please try again.') return redirect('category_request_detail', pk=category_request.pk) except: messages.error(request, 'Uuups, something went wrong, please try again.') return redirect('category_request_detail', pk=category_request.pk) models.py class Category(models.Model): title = models.CharField(max_length=30, verbose_name="Title") description = models.TextField(max_length=200, null=True, blank=False) cover = fields.ImageField(blank=False, null=False, upload_to=get_file_path_static_glued, validators=[default_image_size, file_extension_category_cover], dependencies=[FileDependency( processor=ImageProcessor(format='PNG', quality=99, … -
Django_filters field_name always [invalid name]
I'm making a Search app with django_filters and I would like to change the names of some fields. field_name is not working - it's showing [invalid name] my filterset: class ArticleFilter(django_filters.FilterSet): multi_name_fields = django_filters.CharFilter(method='filter_by_text', field_name="Text", widget=forms.TextInput(attrs={"placeholder": "Suche"})) pub_date = django_filters.DateFromToRangeFilter(field_name="Datum") class Meta: model = Article fields = ["pub_date", "multi_name_fields"] def filter_by_text(self, queryset, name, value): return queryset.filter(Q(pure_text__icontains=value) | Q(title__icontains=value) | Q(description__icontains=value)) -
Django declaration
When declaring an App in the settings.py of the Django project is there a difference between: INSTALLED_APPS = [ /../ 'MyAppHere', # AND 'MyAppHere.apps.MyAppHereConfig', ] -
ValueError at /posts/create/ invalid literal for int() with base 10: 'create' in django Form
I am trying to make Django form in django but this gives me error something like this. ValueError at /posts/create/ invalid literal for int() with base 10: 'create' I don't know where it is coming form. models.py from django.db import models from django.urls import reverse # Create your models here. class Post(models.Model): title = models.CharField(max_length= 120) content = models.TextField() updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) def __unicode__(self): return self.title def __str__(self): return self.title def get_absolute_url(self): return reverse("posts:detail", kwargs={"id": self.id}) #return "/posts/%s/" %(self.id) views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse from .models import Post from .forms import PostForm def posts_create(request): form = PostForm() context = { "form": form, } return render(request, "post_form.html", context) def posts_detail(request, id=None): #instance = Post.objects.get(id=1) instance = get_object_or_404(Post, id=id) context = { "title": instance.title, "instance": instance } return render(request, "post_detail.html", context) forms.py from django import forms from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = [ "title", "content" ]