Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 3.0.3, throttle after X failed login attempts
This is not a duplicate of: Lock out users after too many failed login attempts or How to secure APIs for Registration and Login in Django Rest Framework? I am using Django 3.0.3 and want to integrate protection for brute-force attacks. I want to limit the request rate for failed login attempts per IP. Tried using https://www.django-rest-framework.org/api-guide/throttling/#throttling but this solution does not work since it considers every request and I am only interested in failed attempt. Tried to use Django-Axes but it is not supported for Django 3.0.3 Other packages like Django-Defender are also not compatible. Looked up Django-Ratelimit but it also doesn't support failed login attempts. How can I solve this? It is really frustrating that there isn't a plug-and-play solution for such a common use -
How to use serializer method field to work on primary key related data
I want to use serializer method field to fetch data with some business rule class Product(models.Model): name = models.CharField() class Stock(models.Model): product = models.ForeignKey(Product, on_delete=models.Cascade, related_name='stock') current = models.BooleanField(default=True) quantity = models.IntegerField() class ProductSerializer(serializers.ModelSerializer): productstock = serializers.SerializerMethodField() #GET LATEST CURRENT STOCK-QUANTITU class Meta: model = Product fields = [ 'name', 'productstock' ] I want to get an output like this: { name:'laptop', productstock:18 } -
Django upload csv file - only 1st row save in the db.. What could be wrong?
I am creating a django application and I am trying to a upload a csv file, when uploade only 1 row is save. Please find below sample data. CSV File: first_name, last_name, email, phone, room Juliet, Tolentino, julz@gmaial.com, 1234567, 13 Jiselle, Buena, jis@gmail.com, 45678899, 14 Model: class Teacher(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.CharField(max_length=50) phone = models.CharField(max_length=20) room = models.CharField(max_length=20) photo = models.ImageField(upload_to='photos/%Y/%m/%d/', default='prof_avatar.jpg') created = models.DateTimeField(auto_now_add=True) Views def importteacher(request): if request.method == 'GET': return render(request, 'teachers/importteacher.html') csv_file = request.FILES['file'] if not csv_file.name.endswith('.csv'): return render(request, 'teachers/importteacher.html', {'form': AuthenticationForm(), 'error': 'The file is not a CSV format'}) data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=','): _, created = Teacher.objects.update_or_create( first_name=column[0], last_name=column[1], email=column[2], phone=column[3], room=column[4] ) context = {} return render(request, 'teachers/importteacher.html', context) Form <form method="POST" ENCTYPE="multipart/form-data"> {% csrf_token %} <div class="row justify-content-center mt-5"> <div class="col-md-5"> <h2>Import Teacher</h2> <input class="btn btn-primary" type="file" name="file"> <p>ONLY accepts csv files</p> <button type="submit" class="btn btn-primary">Upload</button> </div> </div> Thanks.Appreciate your response -
video is unplayable after adding static urls
from django.urls import path from .views import homepageview from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('',homepageview), ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) im getting into /static/video/videoname.mp4 and its showing as shown in the fig. -
Why Django doesn't provide a urls.py file for apps?
When we start a new project, we are provided with a urls.py file. However, when we create apps within our project, Django doesn't provide the urls.py file for us and we are expected to create it manually. What is the exact logic/reason behind that? Are there even apps that don't necessarily have to have urls.py file? -
Get value from post method to views from a for loop
I am trying to get a value from template to views.py of a django project. I am able to get the value of name="city" correctly but unable to get the exact value of name="category" in my views, instead I am getting the first element value for all the other elements in the loop. An idea to solve this will be very much helpful. #category.html {% for test in mytypes %} <form id="myform" action="{% url 'my_city_category' %}" method="POST"> {% csrf_token %} <a href="javascript: submitform()"> <div class="col-6 col-lg-3 col-md-4 col-sm-6 col-xl-2 hover-box mt-2 text-center"> <div class="pb-1 pt-2"> <img src="{{test.icon_image.url}}" width="100"/> <h6 class="mt-3 text-body text-capitalize text-decoration-none">{{ test.category_type }}</h6> <input type="hidden" name="category" value="{{ test.category_type }}"># unable to repeat the value while calling it in the views, stuck at the first value <input type="hidden" name="city" value="{{ city }}"> #rendering the exact value </div> </div> </a> </form> {% empty %} <h6 class="mt-3 text-body text-capitalize text-decoration-none">No Categories Listed</h6> {% endfor %} #views.py def City_specific_page(request): city = request.POST.get('city') category = request.POST.get('category') business= Business.objects.filter(city__City=city, type__category_type=category) return render(request, 'community_app/type_detail_city.html',{'business':business,'category':category,'city':city}) #urls.py path('City', views.City_specific_page, name='my_city_category'), -
Making data labels and data for chartsjs form a database using Django
I have a chartsjs chart, and I want the the data labels and data to come from the a database table i created called Floating. First of all I assign and pass the entries of my table and the count of my table in my views.py so i can access them in my index.html file. def index(request): the_numbers_from_Floating = Floating.objects.all() the_count_from_Floating = Floating.objects.count() return render(request, "index.html", { 'the_numbers_from_Floating': the_numbers_from_Floating, 'the_count_from_Floating' : the_count_from_Floating }) There are 2 sections of my chartsjs chart that i want to fill in. These are the labels and the data attributes. So in the labels attribute of my chartjs chart code, i want the chart to generate X amount of labels. X being the number of entries in my Floating table. Hence i want it to be my "the_count_from_Floating". and i want each entry to say "week 1 - week X". labels: [ {% for number in the_numbers_from_Floating %} "week" {% endfor %} ] There are 2 problems with this, the first being nothing the chart doesn't show up because of the for loop i entered. if i hardcode week 1, week 2, week 3 the chart shows up. so the problems is to do with … -
How to post data to the local server using axios
I am working on a social site project, I am using django rest framework as backend react and redux as frontend. I also use axios to interact with my server. Problem: I can send a get request to show my post's list it works properly, but I can't post a new blog to my server. It returns a 403 (Forbidden) error. I checked my code many times but I didn't know what's the problem. Here is the code Action creator // ADD BLOGS ACTION export const addBlog = (blog) => (dispatch) => { axios .post("http://localhost:8000/api/blog", blog) .then((res) => { dispatch({ type: ADD_BLOG, payload: res.data, }); }) .catch((err) => console.log(err)); }; Reducer export default function (state = initialState, action) { switch (action.type) { case GET_BLOGS: return { ...state, blogs: action.payload, }; case ADD_BLOG: return { ...state, blogs: [...state.blogs, action.payload], }; default: return state; } } and it's my form import React, { Component, Fragment } from "react"; import PropTypes from "prop-types"; import { connect } from "react-redux"; import { addBlog } from "../../actions/blogs"; export class Form extends Component { state = { title: "", content: "", // image: "", }; handleChange = (e) => this.setState({ [e.target.name]: e.target.value, }); handleSubmit = (e) … -
I am trying to apply pagination to a list in a popup, but something is not working
I am trying to apply pagination to a list in a popup, but something is not working excuseme I have a question first Posts that were originally printed cannot be printed second The page number output format is strange. event listner code for such button $('body').on('click', '.skill_search_button', function (e) { e.preventDefault(); window.history.pushState("", "", '/wm/myshortcut/') const search_word = $(".skill_input_box").val(); console.log("search_word : " + search_word); $("input:radio.search").each(function () { if (jQuery(this).is(":checked")) { search_option = this.id; } else { } }); $.ajax({ type: "POST", url: 'search_by_id_and_word/', data: { 'search_word': search_word, 'search_option': search_option, csrfmiddlewaretoken: '{{ csrf_token }}' }, success: function (result) { window.history.pushState("", "", '/wm/myshortcut/') $("#wm_list_area_for_popup").html("") $("#wm_list_area_for_popup").append(result) } }); }); The code below is the view and template I tried, but it didn't work view if(search_option == "content+title"): page = request.GET.get('page', '1') object_list = MyShortCut.objects.filter(Q(author = user)).filter(Q(title__icontains=search_word) | Q(content1__icontains=search_word) | Q(content2__icontains=search_word)).order_by('-category') print('object_list(count) :::::: ' , object_list.count() ) # 검색 키워드 "강의"로 검색하면 39 paginator = Paginator(object_list, 10) # 페이지당 10개씩 보여주기 page_obj = paginator.get_page(page) for x in object_list: print("x : ", x) print("page_obj : ", page_obj) return render(request, 'wm/MyShortCut_list_for_search.html', { "object_list":page_obj, "question_list":page_obj }) template 검색 결과: <table border="1" width="100%"> <tr> <td>번호</td> <td>category</td> <td>title 22</td> <td>name</td> </tr> <tbody> {% if object_list.exists %} {% for p in … -
How to save an image with validation Django?
I have the following which is giving me the error: AttributeError: 'PngImageFile' object has no attribute '_committed' Same goes to jpg images. my method in view: def digital_product_edit(request, digital_product_id): digital_product = get_object_or_404(DigitalProduct, pk=digital_product_id) if request.method == 'POST': form = DigitalProductForm(request.POST, request.FILES, instance=digital_product) if form.is_valid(): print(form) digital_product.name = form.cleaned_data['name'] digital_product.image = form.cleaned_data['image'] digital_product.save() return redirect(f'/') else: form = DigitalProductForm(instance=digital_product) return render(request, '/.html', {'form':form, 'digital_product':digital_product}) I have a validation for the form: class DigitalProductForm(forms.ModelForm): class Meta: model = DigitalProduct fields = ['name', 'description', 'image', 'slug'] def clean_image(self): file = self.cleaned_data.get('image', False) image = file.image if image: if image.height > 1920 or image.width > 1080: raise ValidationError("Height or Width is larger than what is allowed") return image else: raise ValidationError("No image found") I tried adding: digital_product.image.save(form.cleaned_data['image'], ImageFile, save=False) under the digital_product.image = form.cleaned_data['image'] but it gives a ImageFile isn't defined even though i tried to import at the top When I remove the validation, the image will upload successfully so it's the validation causing this. It works in checking but something goes wrong when a file is about to be saved. What is missing to have this working? BTW, my images are uploading to AWS S3 -
AttributeError: 'AttributeValueAdmin' object has no attribute 'urls'
I have designed a table for attribute and product attributes. An attribute can have many values. For example, an attribute called color can have values like Black, white, Grey, Maroon etc. For this I designed a table such way However when registering to the admin, I get AttributeError: 'AttributeValueAdmin' object has no attribute 'urls' error. class Attribute(models.Model): name = models.CharField(max_length=30, unique=True) slug = models.SlugField(max_length=250, unique=True) class Meta: verbose_name = "Attribute" verbose_name_plural = "Attributes" def __str__(self): return self.name class ProductAttribute(SortableModel): product = models.ForeignKey(Product, related_name="productattribute", null=True, on_delete=models.CASCADE) attribute = models.ManyToManyField( Attribute, through="AttributeValue" ) class Meta: ordering = ("sort_order",) verbose_name = "Product Attribute" verbose_name_plural = "Product Attributes" class AttributeValue(SortableModel): name = models.CharField(max_length=250) value = models.CharField(max_length=100, blank=True, default="") slug = models.SlugField(max_length=255) productattribute = models.ForeignKey(ProductAttribute, null=True, related_name='productattribute', on_delete=models.CASCADE) attribute = models.ForeignKey( Attribute, related_name="values", on_delete=models.CASCADE ) class Meta: ordering = ("sort_order", "id") unique_together = ("slug", "attribute") def __str__(self) -> str: return self.name admin.py class ProductAdmin(admin.ModelAdmin): model = models.Product prepopulated_fields = {'slug': ('name',), } class AttributeValueAdmin(admin.TabularInline): model = models.AttributeValue extra = 2 class AttributeAdmin(admin.ModelAdmin): model = models.Attribute prepopulated_fields = {'slug': ('name',), } class ProductAttributeAdmin(admin.ModelAdmin): # model = models.ProductAttribute inlines = (AttributeValueAdmin, ) admin.site.register(models.Attribute, AttributeAdmin) admin.site.register(models.AttributeValue, AttributeValueAdmin) admin.site.register(models.ProductAttribute, ProductAttributeAdmin) -
How to develop a voice-calling system in Django
I am developing a Django chat app. I want to add the voice calling system to my app. This app is currently using Django with MySQL database. How can I achieve this? Would I have to use Node.js or similar frameworks? Your help will be appreciated. -
Unknown git problem is not pulling Django database correctly from Heroku. Data is lost on pull / push
Any idea why git is not pulling correctly my django react project's database from heroku? Every time I git pull heroku master, the database appears to be the same as when originally uploaded although being constantly modified and updated. Whatever change or updates in the database while it's at heroku are not being pulled when doing git pull heroku master. And that means all the data that was once in heroku's version of the database gets lost the moment I push from my computer (which will result in the version of the database that my local drive has instead of the updated one that once lived in heroku). Please let me know if I can provide any additional information that is helpful. Thank you! -
Why the loop cannot work in this django views.py
I try to write a login page that will lock the user by inputting the wrong password three times and the username will go to the blacklist so that it will be locked. The login page works well and the blacklist works well. One problem is the loop does not work, I had 'while count < 3' in the beginning, but it only gives the user one chance to input password, then I rewrite the code as 'if elif' format to check what goes wrong. What I find is it stuck on "1 Username or Password is incorrect 1" which means it only goes to the first if and the count always is 1 which means the count goes back 0 every time. I think that because after the user clicks the login button, the page refresh and makes the count 0 again, so how should I solve it? @unauthenticated_user def loginPage(request): if request.method == "POST": username = request.POST.get('username') # Get username input first password = request.POST.get('password') user = authenticate(request, username=username, password=password) BL = BlackList.objects.values_list('list', flat=True) # Read all data into array if username in BL: # Check if the username is in blacklist messages.info(request, 'Username in black list, please … -
How to create custom-simplified word app in django framework?
i am new here, can someone help. how should I create the "word" app in Django,i.e make it. basic features, like an underling, coloring, capitalizing, spacing between right and left edges, font change. Is there and pre-made packages where I can take ideas or any directions to solve. this problem will be helpful. thank you!! -
Django Media Files (Images) Security
I am working on image handling in Django. I am using normal image model storing method. So, my model is something like, class PictureModel(models.Model): def user_directory_path(instance, filename): return 'images/{0}/{1}'.format(instance.user.username, filename) user = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(upload_to=user_directory_path) I have a media root setup as, MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' The url.py setup is as follows, url(r'^static/(?P<path>.*)$', django.views.static.serve, {'document_root': settings.STATIC_ROOT, 'show_indexes': settings.DEBUG}) Now in normal flow, the image uploading and fetching are working as expected. But the issue is regarding the user validation/authentication while fetching the media file. Suppose, I am getting an image by the URL, media/images/user_1/mypic.jpg But the whole media folder gets exposed without any validations and I can access, media/images/user_2/mypic.jpg also through the browser. I have searched on this over the net and found there are some random third party libraries are available but they are not so standard/popular. Can anyone suggest the best practices and libraries to handle the situation. -
Django: How to use a nested serializer for the User field?
I encounter a problem in a CRUD API. The Create function does not work. More concretely, when i create a "story" the "author" of a story cannot be set automatically, because I use a nested serializer for the "author" field (error meassage: author is required). I use this serializer 'UserDetailSerializer ()' to get the username of a author when i retrieve the stories (and not just the user ID) . However, when using the API for creating a story, it is not possible because the author is not set automatically. Now I wonder if I need to create two separate serializers and APIs. One to create, update, delete the sotry and one to retrieve - or can I handle it all in one? I would prefer the option of handling everything in a single API, but I currently see no way to do that. Is my way of thinking correct? And how can i get the full CRUD functionality while using the the nested serializer? class StoryViewSet(viewsets.ModelViewSet): serializer_class = StorySerializer queryset = Story.objects.all() def perform_create(self, serializer): serializer.save(author=self.request.user) class StorySerializer (serializers.ModelSerializer): author = UserDetailSerializer () class Meta: model = Story fields = ('title', 'author', 'id') class UserDetailSerializer(serializers.ModelSerializer): class Meta: model = … -
How to resolve exception in django-main-thread
Please help me in resolving exception in django-main-thread in the image.click here. -
blocked by CORS policy: Request header field access-control-allow-methods is not allowed by Access-Control-Allow-Headers in preflight response
async onSubmit(e) { e.preventDefault(); axios.post('http://127.0.0.1:8000/auth/token/login',{ email:this.state.email, password:this.state.password, }).then(res => { localStorage.setItem('token', JSON.stringify(res.data)); this.props.history.push('/protcted') }); console.log("resgister!"); // console.log(resd.json()); } async componentDidMount() { if (!this.state.logged_in) { this.props.history.push('./login') } console.log(user)); if (this.state.logged_in) { fetch('http://localhost:8000/auth/users/me', { method: 'GET', headers: { "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept, Authorization", "Access-Control-Allow-Methods": "*", "Authorization": `Token ${localStorage.getItem('token')}`, "Content-Type": 'application/x-www-form-urlencoded', "withCredentials": true, "Access-Control-Allow-Origin":"*", 'X-Requested-With': 'XMLHttpRequest' } }) .then(res => JSON.stringify(res.data)) .then(json => { this.setState({ username: json.username }); }); } } settings.py INSTALLED_APPS = [ 'authapp', 'rest_framework', 'djoser', 'rest_framework.authtoken', 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True enter image description here signup complete working this localhost URL but login can not work.and in this onSubmit method completely work token does store in localStorage but I try to authenticate with this token I get this error. And the surprise is I request http://localhost:8000/auth/users/me this URL in Postman then I get data you can see in this that photo in the given link enter image description here -
DRF url route did not match for genericview RetrieveUpdateAPIView
I have added the following routes to my Django Rest framework project, the url is matching well and returns the list view for orders and inventories however it does not match for detail view order/<int:order_no> and inventory/<int:pk> localhost:8000/FD/orders/ work but localhost:8000/FD/order/1/ does not match and returns Using the URLconf defined in FriendsDigital.urls, Django tried these URL patterns, in this order: 1. admin/ 2. ^rest-auth/ 3. ^FD/ ^inventories/$ [name='inventory_list'] 4. ^FD/ ^inventory/<int:pk>/ [name='inventory_edit'] 5. ^FD/ ^orders/ [name='orders_list'] 6. ^FD/ ^order/<int:order_no>/ [name='order_update'] The current path, FD/order/1/, didn't match any of these the same issue is for inventory Urls.py urlpatterns = [ url('^inventories/$', InventoryList.as_view(), name='inventory_list'), url('^inventory/<int:pk>/', InventoryRetrieveUpdate.as_view(), name='inventory_edit'), url('^orders/', BusinessOrderList.as_view(), name='orders_list'), url('^order/<int:order_no>/',BusinessOrderUpdate.as_view(), name='order_update') ] views.py class InventoryList(generics.ListAPIView): queryset= Inventory.objects.all() serializer_class = InventorySerializer class InventoryRetrieveUpdate(generics.RetrieveUpdateAPIView): queryset = Inventory.objects.all() serializer_class = InventorySerializer class BusinessOrderList(generics.ListCreateAPIView): queryset = BusinessOrder.objects.all() serializer_class = BusinessOrderSerializer class BusinessOrderUpdate(generics.RetrieveUpdateAPIView): queryset = BusinessOrder.objects.all() serializer_class = BusinessOrderSerializer Django version - 3.0.7 DjangoRestFramework - 3.11.0 -
Limit Amount Of Files A User Can Upload
I have a multi-file upload and want to limit users to 3 uploads each. My problem is that I need to know how many files a user has already created in the DB and how many they are currently uploading (they can upload multiple files at once, and can upload multiple times). I have attempted many things, including: Creating a validator (the validator was passed the actual file being added, not a model, so I couldn't access the model to get it's id to call if UploadedFile.objects.filter(data_id=data.id).count() >= 4:). Doing the validation in clean(self): (clean was only passed one instance at a time and the DB isn't updated till all files are cleaned, so I could count the files already in the DB but couldn't count how many were currently being uploaded). Using a pre-save method (If the DB was updated between each file being passed to my pre-save method it would work, but the DB is only updated after all the files being uploaded have passed through my pre-save method). My post-save attempt: @receiver(pre_save, sender=UploadedFile) def upload_file_pre_save(sender, instance, **kwargs): if UploadedFile.objects.filter(data_id=instance.data.id).count() >= 4: raise ValidationError('Sorry, you cannot upload more than three files') Thank you. -
HTTPS on EC2 instance running python project
I'm having considerable difficulty getting HTTPS to resolve on my EC2 instance, which runs a python project. The request just times out (ERR_CONNECTION_TIMED_OUT). HTTP runs ok, however. The steps I've taken are as follows. I've created a certificate in ACM for the following domains: *.mywebsite.com and mywebsite.com I've setup Route 53 as follows: Routing policy on the A records is Simple. I've gone into the Listener for my Load Balancer for my EC2 instance and CHANGED the port from 80 (HTTP) TO 443 (HTTPS) and added my certificate. I've then gone into the Inbound Rules for my Security group, and added HTTPS At this point, I've got the following questions: a) Given that this is a python/Django project, is enabling HTTPS for EC2 possible to do this through the aws website or do I need to add config files and deploy to my instance? b) Do I need to create a target group running on HTTPS? c) Do I need listeners on my load balance for port 80 and port 443 or just port 443? d) On my security group, do I need port 80 to go to 0.0.0.0/0 and ::0/? e) Should the A record by the DNS name … -
best coding platform to integrate with django application
We have one application developed in django framework, Now I wanted to have a coding platform/IDE wherein I'll be giving problem statement and user will write code, compile and run to get the solution. Once he submits that code it has to pass the testcases passed by me(or throw the errors, if any). Finally I should get result of problem statement. Is there any third party coding IDE/platform to be integrated with my application(be it open-source/paid) along with all testcases? I've searched for and found judge0,hacker earth APIs which are the compilers by which we could send source code and get output of it which doesn't fulfill my requirements though. Please share if any suggestions/recommendations. -
Django - Prevent a User from Accessing a Page when He/She Typed the URL
I have a page in Django that I don't want to be accessed by anyone except when they clicked the specific link that I made for that page. I'm aware about @login_required but the problem is I want the page to be restricted to EVERYONE. I haven't tried any code yet since I absolutely have no idea how to do it. Even google did not give me answer. Please help -
best way to send data from android->server->another android in realtime
I am currently doing a project that sends sensor data from Arduino to Android(patient's app) then sends those data from android to server, then sends them to another Android(guardian's app). We are using Django for backend. Thus, I am thinking 2 ways to send Data in real-time(every one second). 1.Using Http Rest Api(update MySQL every second from patient's android, and get data from MySQL every second from guardian's android). 2.Django channels which is good for chatting application, and our project seems pretty similar. I have experienced HTTP REST API before, but I am new to socket programming. Which is better way? HTTP rest API vs Django channels?