Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Google oAuth2 getting Internal Server error after redirected to url
In the Django web application, I followed all the neccessary steps for login using google. But after login in through a google account, it will redirect to my local URL but get an Internal server error. I think my google cloud platform settings are right. Because I used same client key and secret key same in another demo Django project, it works fine for that. in google cloud platform redirect URL is -- http:localhost:8000/oauth/complete/google-oauth2/ How to fix these? -
DRF File Upload, How can I solve File missing Error?
400 Error {"detail":"Missing filename. Request should include a Content-Disposition header with a filename parameter."} I want to upload file via DRF FileUploadParser But Error occurs below Bad Request: /api/activities/40/chapter/1/upload [09/Nov/2021 16:44:33] "POST /api/activities/40/chapter/1/upload HTTP/1.1" 400 109 And my codes in views.py about that error are this. class FileView(APIView): parser_classes = (FileUploadParser,) def post(self, request, format=None, *args, **kwargs): if 'file' not in request.FILES: raise ParseError("Empty content") f = request.FILES.get('file') print(f) print(dir(request)) print(request.__dict__) addAttr = request.data.dict() file_name = request.data['filename'] new_file_full_name = file_upload_path(file_name.name) file_path = '/'.join(new_file_full_name.split('/')[0:-1]) #model Attr addAttr['activityid'] = request.parser_context['kwargs']['pk'] addAttr['chapterid'] = request.parser_context['kwargs']['chapterid'] addAttr['filepath'] = file_path addAttr['filename'] = file_name addAttr['fileext'] = os.path.splitext(file_name.name)[1] addAttr['create_date'] = datetime.datetime.now() addAttrDict = QueryDict('', mutable=True) addAttrDict.update(addAttr) fileSerializer = ChapterfileSerializer(data = addAttrDict, files=request.FILES) if fileSerializer.is_valid(): fileSerializer.save() print(fileSerializer.data) return Response(status=status.HTTP_201_CREATED) else: print(fileSerializer.errors) return Response(fileSerializer.errors, status=status.HTTP_400_BAD_REQUEST) If I add a parameter "filename", 500 error occured. TypeError: post() missing 1 required positional argument: 'parameter' [09/Nov/2021 16:48:35] "POST /api/activities/40/chapter/1/upload HTTP/1.1" 500 86716 ReactJS page sends File to my Django API Server. activityid and chapterid are Board and Post ID. SO, I need these insert to DB. How can I solve this? -
How do I change stroke fill color (RGB) in python
how do I change stroke fill color (RGB) in python Showing Error: TypeError: color must be int or single-element tuple from PIL import Image from PIL import ImageDraw from PIL import ImageFont, ImageOps label2 = "VIKRAM" font = ImageFont.truetype('D:/vikram/pythonProject/fonts/B5______.TTF', 120) line_height = sum(font.getmetrics()) fontimage2 = Image.new('L', (font.getsize(label2)[0], line_height)) ImageDraw.Draw(fontimage2).text((0, 0), label2, stroke_width=10, stroke_fill=(0, 0, 0), fill=255, font=font)-------->stroke fill in (RGB) fontimage2 = fontimage2.rotate(330, resample=Image.NEAREST, expand=True) orig = Image.open('F:/desktop/sunshine girl/PSI Sunshine Theme Girl Personalized Eye Mask.png') orig.paste((220, 32, 37), box=(400, 200), mask=fontimage2) orig.show() -
unique_together does not prevent duplicate records
I have two models like this : class Preference(models.Model): lat = models.DecimalField(max_digits=25,decimal_places=15) lng = models.DecimalField(max_digits=25,decimal_places=15) name = models.CharField(max_length=150,null=True) address = models.TextField(max_length=350,null=True) type = models.CharField(max_length=150,blank=True,null=True) class PrefenceOfUser(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) place_detail = models.ForeignKey(Preference, on_delete=models.CASCADE) def __str__(self): return self.user.username class Meta: unique_together = ('user', 'place_detail',) this is the json i post to my apiview : { "lat": "29.621142463088336", "lng": "52.520185499694527", "name":"cafesama1", "address":"streetn1", "type":"cafe" } in views.py : class PreferedLocationsOfUsers(APIView): def post(self, request, format=None): serializer = PreferLocationSerializer(data=request.data) if serializer.is_valid(): location= Preference(**serializer.data) location.save() user_perefeces = PrefenceOfUser(user=request.user,place_detail=location) user_perefeces.save() return Response({'location saved'},status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) i want to prevent the user to save dublicated records in database but when location object is saved in PrefenceOfUser unique_together does not prevent dublicating. any idea why?