Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django searching multiple models and removing duplicates
I am trying to build a search function for my blog that searches through the two models Articles and Spots. The two models are connected via the pivot table ArticleSpots. My blog is structured so that there are multiple spots in each article. When a query is searched I want the query to be searched within both models but only display clickable articles. I have a html page for each article but not for each spots, so all the spots that resulted from the search have to be shown as the article which contains the spot. Hope that makes sense! This is the code that I came up with but the problem is that I get a lot of duplicates in the variable results. There are duplicates within each articles_from_spots and articles_from_query, and there are also overlaps between them. Is this the right way to accomplish this ? How can I remove the duplicates from the results? Any help would be appreciated! views.py def search(request): query = request.GET.get("q") articles_from_query = Articles.objects.filter( Q(title__icontains=query) | Q(summary__icontains=query) ) spots_from_query = Spots.objects.filter( Q(title__icontains=query) | Q(summary__icontains=query) | Q(content__icontains=query) ) articles_from_spots = [] for x in spots_from_query: article = Articles.objects.filter(articlespots__spot=x) articles_from_spots.extend(article) results = chain(articles_from_spots, articles_from_query) context … -
Django: custom storage system with incremental number
I'm trying to creare a custom storage file system in python to have the duplicate files that are uploaded to be different by a number that increment. The code is kinda working, my only problem is that instead having this kind of results: nameofthefile_1.txt nameofthefile_2.txt nameofthefile_3.txt I get this nameofthefile_1.txt nameofthefile_1_2.txt nameofthefile_1_2_2.txt This is my code class CustomStorage(FileSystemStorage): def get_available_name(self, filename, max_length=None): number_1 = filename.split('_')[19] plus_one = int(number_1.split('.')[0]) if self.exists(filename): plus_one += 1 dir_name, file_name = os.path.split(filename) file_root, file_ext = os.path.splitext(file_name) filename = os.path.join(dir_name, '{}_{}{}'.format(file_root, plus_one, file_ext)) return filename def user_directory_path(instance, filename): extension = filename.split('.')[-1] filename = "file_%s_1.%s" % (instance.identification, extension) return 'folder/{0}/{1}'.format(instance.user, filename) -
Adding a panel black behind a form
I currently have a form in my app that looks like this: However I would like to add a white panel behind the form, the panel must still show the background behind it When I use the <div class="panel panel-default" style="color: white "> it does not add this Does anyone know how I can add this with HTML / CSS Please see the below code for assistance: {% extends "main/base.html"%} {% block content %} <div class="opacity-50"> <body id="bg" style="background-size: cover; background-repeat: no-repeat;background-image: url('https://images.unsplash.com/photo-1518334792104-db78a16ac8b8?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1470&q=80')";> </body> </div> <div class="panel panel-default" style="color: white "> <from> <div style="text-align: center"> <h1>Sign Up with Shiftly</h1> <p>Please complete the form below carefully, ensure you provide the correct information and documents to avoid your application being delayed.</p> </div> <h2 style="text-align: left; padding-left: 250px">PERSONAL INFORMATION</h2> <br> <div style="text-align: Left; padding-left: 255px"> <div class="row mb-2" style="width: 100%"> <div class="col-6 col-sm-2"> Title {{ form.title }}</div> <div class="col-6 col-sm-3"> Initials {{ form.initials }} </div> <div class="col-6 col-sm-3"> First Name(s) {{ form.firstname }} </div> <div class="col-6 col-sm-3"> Surname {{ form.surname }} </div> </div> <div class="row mb-2" style="width: 100%"> <div class="col-6 col-sm-3"> Preferred Name {{ form.prefferedname }}</div> <div class="col-6 col-sm-2"> Gender {{ form.gender }} </div> <div class="col-6 col-sm-3"> Date Of Birth{{ form.dob }} </div> … -
How can gunicorn handle hundreds of thousands of requests per second for django?
From the docs - How many workers, DO NOT scale the number of workers to the number of clients you expect to have. Gunicorn should only need 4-12 worker processes to handle hundreds or thousands of requests per second. Generally we recommend (2 x $num_cores) + 1 as the number of workers to start off with. From threads, The number of worker threads for handling requests. Run each worker with the specified number of threads. A positive integer generally in the 2-4 x $(NUM_CORES) range. You’ll want to vary this a bit to find the best for your particular application’s workload. Now the question is what no of threads and workers can serve hundreds or thousands of requests per second? Let's say I have a dual-core machine and I set 5 workers and 8 threads. And I can serve 40 concurrent requests? If I am going to serve hundreds or thousands of requests, I'll need a hundred cores? this line is very hard to understand: Gunicorn should only need 4-12 worker processes to handle hundreds or thousands of requests per second. -
Filter products using Category Model in Django
I'm building an ecommerce website and want to filter products using categories but I don't know how to render the products. And add the categories in the navigation bar from where people can navigate to different categories. Here's my views.py file: from django.shortcuts import render from django.views import View from .models import Product, Category class ProductView(View): def get(self, request, *args, **kwargs): products = Product.objects.filter(is_active = True) context = { 'products': products, } return render(request, 'Product/products.html', context) class ProductDetailView(View): def get(self, request, slug): product = Product.objects.get(slug = slug) context = { 'product': product } return render(request, 'Product/productdetail.html', context) class CategoryView(View): def get(self, request): category = Category.objects.all() products = Product.objects.filter(category__slug = slug) context = { 'category': category, 'products':products, } return render(request, 'Product/category.html', context) And this is my models.py from django.db import models from Seller.models import Seller class Category(models.Model): category = models.CharField(max_length = 255) slug = models.SlugField(max_length = 255) def __str__(self): return self.category class Product(models.Model): product = models.ForeignKey(Seller, on_delete = models.CASCADE) title = models.CharField(max_length = 255) image = models.ImageField(upload_to = 'images', null = True, blank = True) file = models.FileField(upload_to = 'files', null = True, blank = True) actual_price = models.PositiveIntegerField(default = '0') selling_price = models.PositiveIntegerField(default = '0') slug = models.SlugField(max_length = 255, … -
How to keep a property value in django.values()?
I have my model as: .... created_at = models.DateTimeField(auto_now_add=True, db_column="order_date", null=True, blank=True) @property def created_date(self): return self.created_at.strftime('%B %d %Y') I want to get created_Date in my views.py data = Subs.objects.values('somevalues','created_date') It throws an error. How to access created_date so that i can use it here. -
Django model allow only once in many
Please excuse the title but I'm not sure howto put this into words. I have a model "card" and a model "computer": class card(models.Model): name=models.CharField( verbose_name = 'Name', max_length=50, null=True, blank=True, ) serial=models.CharField( verbose_name = 'Serial', max_length=50, null=True, blank=True, ) class computer(models.Model): name=models.CharField( verbose_name = 'Name', max_length=50, null=True, blank=True, ) slot1 = models.OneToOneField( 'card', related_name='cardslot1', on_delete=models.SET_NULL, null=True, blank=True, verbose_name = 'Slot 1', ) slot2 = models.OneToOneField( 'card', related_name='cardslot2', on_delete=models.SET_NULL, null=True, blank=True, verbose_name = 'Slot 2', ) (Of course that this computer model is invalid) The cards are unique and should only be allowed to be used in one slot - of any computer. What's the best way to achieve this? I was thinking about a in-between table, something like card n-1 cardcomputer n-1 computer but I'm hoping there's a better way I'm not seeing right now. Thanks -
Override User's check password in Django
I am migrating a PHP backend to Django and I don't wanna make users change their passwords. In PHP I'm using Bcrypt, which uses version 2y, while Django uses 2b, making it incompatible. I've read other solutions where people write a whole new hasher, but that seems too difficult. My solution was to override the check_password() function of my User model: def check_password(self, raw_password): alg_prefix = 'bcrypt_php' if self.password.startswith(alg_prefix): return bcrypt.checkpw(bytes(raw_password, 'utf-8'), bytes(self.password[len(alg_prefix):], 'utf-8')) else: return super().check_password(raw_password) And to save old passwords adding bcrypt_php in the beginning. The question is: Is it dangerous to do this? Am I putting my passwords or my system in danger? -
DRF Can't get data for restricted URLs
I'm using simple_JWT and I have a view that requires logged-in users. When I try to send a request (tested with postman, curl, ...) I get 'Authentication credentials were not provided'. views.py : class CurrencyDetailAPIView(generics.RetrieveAPIView): serializer_class = CurrencyDetailSerializer lookup_field = "slug" permission_classes = [IsAuthenticated] settings.py : REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework_simplejwt.authentication.JWTAuthentication", ], } -
× Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'access')
I'm using react and redux to create simple user authentication. When I click on the login button the user get's authenticated, yet the user remails null. Below is the code for auth action and reducer Auth Acction _____________ import axios from 'axios'; import { LOGIN_SUCCESS, LOGIN_FAIL, USER_LOADED_SUCCESS, USER_LOADED_FAIL,} from './types'; export const load_user = () => async dispatch =>{ if(localStorage.getItem('access')){ const config = { headers: { 'Content-Type':'application/json', 'Authorization': `JWT ${localStorage.getItem('access')}`, 'Accept': 'application/json' } }; try{ const res = await axios.post(`${process.env.REACT_APP_API_URL}/account/login`, config) dispatch({ type: USER_LOADED_SUCCESS, payload: res.data }) } catch (err){ dispatch({ type: USER_LOADED_FAIL, }) } }else { dispatch({ type: USER_LOADED_FAIL, }) } }; export const login = (email, password) => async dispatch => { const config = { headers: { 'Content-Type':'application/json' } }; //const body = JSON.stringify({email, password}); const body = {email, password}; const data = JSON.stringify(body); try{ console.log(data) const res = await axios.post(`${process.env.REACT_APP_API_URL}/account/login`, data, config) dispatch({ type: LOGIN_SUCCESS, payload: res.data }) dispatch(load_user()); } catch (err){ dispatch({ type: LOGIN_FAIL, }) } } Auth Reducer import { LOGIN_SUCCESS, LOGIN_FAIL, USER_LOADED_SUCCESS, USER_LOADED_FAIL,} from '../actions/types' const initialState = { access: localStorage.getItem('access'), refresh: localStorage.getItem('refresh'), isAuthenticated: null, user: null }; const authReducer = (state = initialState, action) => { const { type, payload } = … -
How to specify camera capture in input tag using Django?
I'm currently developing an application using Django. I want to open up camera capture directly when specified as follows in HTML5 tag using Django. <input type="file" accept="image/*" capture="camera"/> In this case, how can I make a field in a model? Thanks in advance. Django 3.2.9 -
django queryset values() to string or json
I'm trying to convert my dict to a list of string. this is what generated by django froms list of student I want to have a list without the {''} My forms : students= ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple( attrs={'class': 'displaynone'}), queryset=Student.objects.exclude(present=True).order_by( 'name').values('name'), required=False, label="Choice Students" ) and template {% for i in form.students %} {{ i }} {% endfor %} and I know I can juste do queryset=Student.objects.exclude(present=True).order_by('name') without the values() but I juste want to retreive the name. It will optimize the load of my page. -
Django system always logged user A out when user B logged in
I developed an lite web system with django2.2. When i deployed the project on a server,it ran well when only one user using the web system. while another user(not the same user)logged in the system,the previous one was logged out immediately. The settings about the session in the setting.py file is like below: SESSION_COOKIE_AGE = 518400 SESSION_EXPIRE_AT_BROWSER_CLOSE = False SESSION_SAVE_EVERY_REQUEST = True SESSION_ENGINE = 'django.contrib.sessions.backends.db' Currently, I have no ideas about the issues.Thanks in advance if anybody could help. -
Unable to send data to database in Django
I am an absolute beginner in Django development & I am unable to send the data to my database via the POST method. Please guide me on what is wrong with my approach. My model worked perfectly and I can now access my desired table on my Django admin. The function that I have created in views.py always executes the else condition. From views.py: from django.shortcuts import render, HttpResponse, redirect from app.models import Tbl_Feedback def myform(request): return render(request, 'form.html') def getfeedback(request): if request == "POST": a = request.POST.get('a') objTbl_Feedback = Tbl_Feedback(a="a") objTbl_Feedback.save() return redirect("/") else: return HttpResponse('Form Not Submitted') From models.py: from django.db import models # Create your models here. class Tbl_Feedback(models.Model): fdbk = models.CharField(max_length=120) From urls.py(app): from django.contrib import admin from django.urls import path from app import views urlpatterns = [ path('',views.myform,name="form"), path('getfeedback', views.getfeedback, name="feedback") ] From urls.py(project): from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path("", include("app.urls")) ] Html: <!DOCTYPE html> <html lang="en"> {% load static %} <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Form</title> {% load static %} <link rel="stylesheet" href="{%static 'css.css'%}"> </head> <body> <form action="getfeedback" method="post" > {% csrf_token %} <div class="frame"> <div class="frame-header">FeedBack Please !</div> <div … -
saving foreign key relations using DRF
I am trying to save foreign key relations using serializer , i don't know where i am wrong here i have spend hours thinking about his now , don't seem to understand where the error lies class Catalogs(viewsets.ModelViewSet): queryset = Catalog.objects.all() serializer_class = CatalogSerializer def create(self, request, *args, **kwargs): if request.data: serialized_data = self.get_serializer( data = request.data ) serializer class CatalogSerializer(serializers.ModelSerializer): catalog_products = CatalogProductsSerializer(source = 'catalogproducts_set',many=True) def create(self,validated_data): client_id = validated_data.pop('id') catalog_obj = Catalog.objects.create( client = User.objects.get(id=client_id), ) CatalogProducts.objects.create( catalog = catalog_obj, **validated_data ) return catalog_obj class Meta: model = Catalog fields = ['created_by','client','catalog_products','created_datetime','is_active'] -
How to access the request in models.py, django
@property def get_maca(self, request): if request.user.name == "example": return self I want to do something like this. If the user name is example return that object. How to access the request like this? -
Django+MongoDB: API to populate a collection with data from other collection
I'm trying to create an API in django rest-framework service to perform the following: Whenever the API is called (GET), I need to check all documents in old collection say OldCollection. Go through the OldCollection for relevant fields say ID, Field1, Field2. If Field2 is more than 100, then create a document in new collection with fields NewID, NewField1, NewField2. These fields are not dependant on old collection. API to return how many records got created on the new collection. I'm just getting started with rest framework. Looking for ways to achieve the above mentioned. Can anyone show how view function looks like? -
connection limit exceeded for mongo from aws
When I am trying to put requests from AWS cloud9 environment to Mongo DB Atlas, connectivity with MongoDB is slowed down. To add, while putting query on MongoDB, python code is taking time to fetch the data from database and even hanged. Ours is a free tier and I think the concurrent connection limit is 500. The problem arise after 2-3 weeks. Can we buy some connections? Or how to increase the connection limit. -Amar -
Inputs of form don't show anything
I use Nicepage to generate the html code. Here I have a grid with 3 columns and in each one there is a table then in each table I want to put a Django form. First I could not write anything in the inputs until I added style="display: block;z-index: 1" in first td of table. Now I can write inside the inputs and form works fine but inputs do not show anything; when I write a word inside it, it remains blank but actually word is there and form detects it . here the code : <section class="u-clearfix u-image u-section-1" id="sec-bf5a" data-image-width="640" data-image-height="480"> <div class="u-clearfix u-sheet u-sheet-1"> <div class="u-clearfix u-expanded-width u-gutter-22 u-layout-wrap u-layout-wrap-1"> <div class="u-gutter-0 u-layout"> <div class="u-layout-row"> <div class="u-container-style u-effect-fade u-hover-box u-layout-cell u-opacity u-opacity-60 u-radius-30 u-shape-round u-size-20 u-layout-cell-1" data-animation-name="" data-animation-duration="0" data-animation-delay="0" data-animation-direction=""> <div class="u-back-slide u-container-layout u-opacity u-opacity-60 u-palette-3-dark-2 u-container-layout-1"> <h2 class="u-text u-text-default u-text-white u-text-1">Login Here </h2> <h5 class="u-text u-text-default u-text-white u-text-2">Already a member&nbsp;</h5> <div class="u-table u-table-responsive u-table-1"> <table class="u-table-entity"> <colgroup> <col width="100%"> </colgroup> <tbody class="u-table-body"> <tr style="height: 26px;"> <td class="u-border-6 u-border-palette-3-dark-1 u-table-cell" style="display: block;z-index: 1"> <p style="color:{{color}};font-size:14PX;background-color:LightYellow;text-align: center">{{ER}}</p> <p> <form action="{% url 'docs:login' %}" method="post"> {% csrf_token %} {{form.as_p}} <input style="background-color: #675e39" type="submit" value="ENTER"> </form> </td> </tr> </tbody> </table> … -
Django Formset Required fields in formset validation
I have problems with formset, where I don't know why, can't prefill initial values and formset throws back errors "This field is required.". I thought that when I give queryset to filter forms, they will be prefilled with values given. So how to make this right? Thank you for answers. forms.py class CompositionForm(ModelForm): positionId = PositionsChoiceFields(queryset=Position.objects) class Meta: model = Players fields = ("positionId", ... ) labels = {"positionId": "Nas", ... } widgets = {} for i, f in enumerate(fields[1:]): widgets[f] = forms.TextInput( attrs={"disabled": True, "class": "show-input-as-text form-control flex-fill", "required": "false"}) def __init__(self, *args, **kwargs): super(CompositionForm, self).__init__(*args, **kwargs) PlayersFormSet = modelformset_factory(Players, form=CompositionForm,) views.py class CompositionView(BaseView): template_name = "..." def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context def get(self, *args, **kwargs): # context = self.get_context_data(**kwargs) context = {} team = Teams.objects.get(userId=self.request.user.id) formset = PlayersFormSet(queryset=Players.objects.filter(teamId=team, ), ) context["formset"] = formset return render(self.request, self.template_name, context=context) def post(self, *args, **kwargs): context = self.get_context_data(**kwargs) team = Teams.objects.get(userId=self.request.user.id) form = PlayersFormSet(data=self.request.POST, queryset=Players.objects.filter(teamId=team)) form.clean() print(form.errors) print(self.request.POST) print(form.is_valid()) return render(self.request, self.template_name, context=context) [{'positionId': ['This field is required.'], ... <QueryDict: 'form-TOTAL_FORMS': ['5'], 'form-INITIAL_FORMS': ['4'], 'form-MIN_NUM_FORMS': ['0'], 'form-MAX_NUM_FORMS': ['1000'], 'form-2-positionId': ['1'], 'form-3-positionId': ['1']}> False -
What does the logger 'django.server' do? Is the logger 'django' not enough?
I need to only add the logger which logs all the api requests coming to my server. In the documentation, django.request Log messages related to the handling of requests. 5XX responses are raised as ERROR messages; 4XX responses are raised as WARNING messages. Requests that are logged to the django.security logger aren’t logged to django.request. django.server Log messages related to the handling of requests received by the server invoked by the runserver command. HTTP 5XX responses are logged as ERROR messages, 4XX responses are logged as WARNING messages, and everything else is logged as INFO. I tried disabling django.server and all I could find was that API requests are no longer logged. So, I thought maybe it is for requests emanating from my server. Nope. Still nothing. So what does django.server do? -
How to handle freezing libraries in production with Django?
I have a Django application where I use pipenv to manage packages. Now I want to freeze all the libraries to their current versions to avoid problems in the production. Is it enough just to lock the versions in the Pipfile, or should I handle the dependency packages as well? These are my packages from the Pipfile: [packages] Django = "*" djangorestframework-simplejwt = "*" django-rest-framework = "*" django-cors-headers = "*" pytest-django = "*" psycopg2-binary = "*" If I run the command pipenv run pip freeze > requirements.txt I get a long list of packages and versions because it contains also the packages that my Pipfile packages are dependent of. So should I lock all those packages also, or is it enough to lock the packages in the Pipfile to prevent any unwanted changes happening? -
Issue with google analytics widget
Google analytics widget looks like this in admin page: When I press on the message, this error appears: The error is in the file "venv/lib/site-packages/django/forms/boundfield.py", in the following function: def as_widget(self, widget=None, attrs=None, only_initial=False): """ Render the field by rendering the passed widget, adding any HTML attributes passed as attrs. If a widget isn't specified, use the field's default widget. """ widget = widget or self.field.widget if self.field.localize: widget.is_localized = True attrs = attrs or {} attrs = self.build_widget_attrs(attrs, widget) if self.auto_id and 'id' not in widget.attrs: attrs.setdefault('id', self.html_initial_id if only_initial else self.auto_id) return widget.render( name=self.html_initial_name if only_initial else self.html_name, value=self.value(), attrs=attrs, renderer=self.form.renderer, ) where widget can be TextInput or Textarea from this: from django.forms.widgets import Textarea, TextInput However in the file "venv/lib/site-packages/django/forms/widgets.py" the widget class contains this render function which contains renderer as parameter: def render(self, name, value, attrs=None, renderer=None): """Render the widget as an HTML string.""" context = self.get_context(name, value, attrs) return self._render(self.template_name, context, renderer) Can anyone help me with this? -
How to loop scrapping data and show it
So i try to scrape multiple data, and show it, but the data is dynamic so i use for loop to do that, in the for loop statement it work fine, but when i try to show it in html file it give me the wrong data or data that i dont want to show it. I have try to reverse,change and whateven thing to fix that but still not working this is my script part, when i try to loop the scrapping data. views.py def home(request): test = "" html_content = get_html_content(test) from bs4 import BeautifulSoup soup = BeautifulSoup(html_content, 'html.parser') product = soup.findAll('div',class_="s-result-item") for p in product: productCount = 1 productCount += 1 productDetail = dict() productDetail['product'] = product productDetail['name'] = p.find('span',class_="a-text-normal") # print(productDetail['name']) return render(request, 'app/core_home.html', {'productDetail':productDetail,'product':product}) and this is my html file, where i show the data. core_html.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> {{product_view}} </body> </html> and when i try to run in the html file return nothing i have try many times, and researching but when i search on google what appears is something I don't need, or not a solution to my problem. … -
get() missing 1 required positional argument: 'to_date'
I am trying to filter the users that are created between certain dates, I am using the filter method. But i am having a problem passing the arguments, how can i pass the argument in a correct fashion, this is what i have tried so far. views.py class RegisteredUserFilter(APIView): serializer = RegisteredUserFilterSerializer def get(self, from_date, to_date): userondate = User.objects.filter(created_at__range=[from_date, to_date]).values() users = [] for user in userondate: users.append(user['username']) return Response({"User": users}) serialzers.py class RegisteredUserFilterSerializer(serializers.Serializer): from_date = serializers.DateField() to_date = serializers.DateField() model = User full code here: https://github.com/abinashkarki/rest_framework_authentication/tree/master/authapp while doing this i am getting: TypeError: get() missing 1 required positional argument: 'to_date' How should the argument be passed?