Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to upload multiple image django DRF from Flutter
I have models Car and CarImage and serializers: class Car(models.Model): title = models.CharField('title',max_length=200) def __str__(self): return self.title class CarImage(models.Model): car = models.ForeignKey(Car,on_delete=models.CASCADE,related_name='car_image',related_query_name='car_image') image = models.ImageField(upload_to='test_media/',null=True,blank=True,) def __str__(self): return f'{self.id} Image' class Car_Image_Serializer(serializers.ModelSerializer): class Meta: model = models.CarImage fields = ('id','image') class Car_Serializer(serializers.ModelSerializer): car_image = Car_Image_Serializer(many=True,required=False) class Meta: model = models.Car fields = ('title','car_image') def create(self, validated_data): if 'car_image' in validated_data: car_image= validated_data.pop('car_image') car_instance= models.Car.objects.create(**validated_data) for img in car_image: models.CarImage.objects.create(car=car_instance,image=img) return car_instance if 'car_image' not in validated_data: car_instance= models.Car.objects.create(**validated_data) return car_instance and in flutter I send images with library Dio: FormData formData1 = FormData.fromMap({ 'title': 'test', 'car_image': [ { 'car_image': await MultipartFile.fromFile( image_path, filename: fileName, ) } ] }); var response = await dio.post( url, data: formData1, ); and I get OrderedDict() { "title": "test", "car_image": [ { "id": 7, "image": "https://temike.pythonanywhere.com/media/OrderedDict()" } ] } -
device_detail() missing 1 required positional argument: 'pk'
im currently stuck on a error: device_detail() missing 1 required positional argument: 'pk' I cant seem to get past this error My codes: urls.py path('device/<int:pk>/', DeviceDetailView.as_view(), name='device-detail'), path('device/device_detail/', views.device_detail, name='device-detail'), views.py class DeviceDetailView(DetailView): model = Device template_name = 'interface/device_detail.html' def device_detail(request, pk): device = Device.objects.get(pk=pk) return render(request, 'interface/device_detail.html',{'devices':device}) -
Django - Is it possible to create a event/trigger based scheduler?
Normally what we do is a time-based scheduler, which may repeat after certain period of time. But for some reason, I want to create a trigger-based scheduler. If I have n rows in a table_1 then I need to create n scheduler. So I create another table (called table_2) that stores a scheduler name (randomly generated), for each new record in table_1. I receive real-time data from an API, now if some condition is matched by any of the rows in table_1, I need to trigger the scheduler from table_2 related to that row. I am little bit confuse how to trigger scheduler once all the condition is matched for the related row. Does anyone have any suggestions? Thanks -
Removing pycache files from Django project
Recently I have tried cloning my production code to a different pc. Then I have connected my project to a blank DB and run the command python manage.py makemigrations and after that, I can see that my migrations folder was updated with some pycache files. URL: /folder/app/migrations/pycache I know that the migrations files are very important but here the problem is the production DB contains data and the DB in that different PC is empty. I think if I push these pycache files to the production it might create conflict. My idea is not to push these pycache files(/folder/app/migrations/pycache) into my production environment and ignore them using the gitignore(as I am using git for version control). Am I doing the right thing? and Should/can I gitignore all the pycache files from the project. -
How to add a text editor and compiler in a django page
I am currently working on a project ,where I have to add a text editor and a compiler into my page.I have to also give a functionality, for the user to execute the code and display it on the html page. Here is an example page. https://www.w3schools.com/python/trypython.asp?filename=demo_compiler I want to create a page like this.Where do I start? (I have made a text area where the user can write python code.Then I execute that text file on the server with exec(code_from_textarea).But I found out this is dangerous.So I am stuck) -
How to delete image using image_id with image_id pass as a parameter in django rest framework
How to delete image using image_id with image_id pass as a parameter in django rest framework -
python module schedule not working as expected in cloud foundry
I am using the python schedule module in my cloud foundry application. when tested on the local system, it worked perfectly. when deployed the same application in cloud foundry, I am getting timeout cf error log- 2021-08-11T11:41:25.34+0530 [APP/PROC/WEB/0] ERR [2021-08-11 06:11:25 +0000] [7] [CRITICAL] WORKER TIMEOUT Please suggest. -
Can CalDav be used with my own django calendar app?
I have been reading about CalDav recently but I don't get how it exactly works. I have implemented a calendar app with django rest framework and react js and I want to sync calendars in my own database with my mobile calendar app. Can it be done using CalDav? Is there any solution to do so? Thanks for your help. -
Insert into Django JsonField without pulling the content into memory
Have a Django model class Employee(models.Model): data = models.JSONField(default=dict, blank=True) This JSONField contains two year of data, like a ton of data. class DataQUery: def __init__(self, **kwargs): super(DataQUery, self).__init__() self.data = kwargs['data'] # Then We have dictionary call today to hold daily data today = dict() # ... putting stuff in today # Then insert it into data with today's date as key for that day self.data[f"{datetime.now().date()}"] = today # Then update the database Employee.objects.filter(id=1).update(data=self.data) I want to insert into data column without pulling it into memory. Yes, I could change default=dict to default=list and directly do Employee.objects.filter(id=1).update(data=today) BUT I need today's DATE to identify the different days. Is there a way I could insert today dictionary with date as key without pulling the data column into memory? -
I want to show a random images from a directory (Images) and show in Template in Django
I take the help of This git link but i am still not getting what to do next This is my Setting.py """ Django settings for randomfiles project. Generated by 'django-admin startproject' using Django 3.2.6. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-d(v57c_(x8d5f^kl^@8q2*fy&@-5e93g$@1(#uhn2lwfjda9mw' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'random_images' ] MIDDLEWARE = [ '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', ] ROOT_URLCONF = 'randomfiles.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ["templates"], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'randomfiles.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { … -
Django prints error when PermissionDenied exception raises
In our project, we have used django SessionMiddleware to handle users sessions and it's working fine. The only problem here is when PermissionDenied exceptions happens, an error and its traceback will be printed out in the console! However as expected, by raising that exception, the 403 page will show to the user, but I think it doesn't seem rational, because the middleware here is handling the exception! Just like not found exception, I expect no error in the console. Is there anything wrong?! here is the middleware settings: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django_otp.middleware.OTPMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'axes.middleware.AxesMiddleware', ] And here's the printed error: Forbidden (Permission denied): /the/not_allowed/page Traceback (most recent call last): File "/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python3.8/contextlib.py", line 75, in inner return func(*args, **kwds) File "/our_project/base/decorators.py", line 88, in wrapper return view_func(request, *args, **kwargs) File "/venv/lib/python3.8/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/venv/lib/python3.8/site-packages/django/contrib/auth/decorators.py", line 20, in _wrapped_view if test_func(request.user): File "/venv/lib/python3.8/site-packages/django/contrib/auth/decorators.py", line 70, in check_perms raise PermissionDenied django.core.exceptions.PermissionDenied -
Modify django model form field with widget
I want to modify some fields in model form, and i found two methods: First Method: class ProfileForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['bio'].widget.attrs.update({'placeholder': 'Enter your bio here'}) class Meta: model = Profile fields = ['bio'] Second Method: class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['bio'] widgets = { 'bio': Textarea(attrs={'placeholder': 'Enter your bio here'}) I just want to know if they are the same? Which is better? Or is there another better way? Thankyou. -
How can I fix "Command errored out with exit status 1" when installing requirements.txt through pip for a django project?
I'm having trouble installing this requirements.txt file for a django project. My project directory looks like this: decker-cms ├── decker_cms │ ├── account │ ├── beanstream │ ├── blog │ ├── [...project stuff] ├── decker │ ├── [...env stuff] When I try to run the following command: pip3 install -r requirements.txt from within the decker_cms directory. I get the following error: ERROR: Command errored out with exit status 1: /Users/userk/decker-cms/decker/bin/python3 -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/1y/pymk85y10l1cfkrh92s3n46h0000gn/T/pip-install-ow_x_27c/reportlab_cb76b6eba8ca413ca98c7cbe92425675/setup.py'"'"'; __file__='"'"'/private/var/folders/1y/pymk85y10l1cfkrh92s3n46h0000gn/T/pip-install-ow_x_27c/reportlab_cb76b6eba8ca413ca98c7cbe92425675/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/1y/pymk85y10l1cfkrh92s3n46h0000gn/T/pip-record-3hnbigmk/install-record.txt --single-version-externally-managed --compile --install-headers /Users/userk/decker-cms/decker/include/site/python3.9/reportlab Check the logs for full command output. I installed the project prerequisites: gif, python, pip3, Postgres 10.10 and npm. How can I go about solving this? -
Send Django Email User Register Confirmation with with custom header name
I want to send Django email confirmation email, it shows the admin added email address (that we configure in settings.py) as the header of the newly arrived email, but I want to change it to something else my personal Header Title, like The Google Team, I want to replace my email as others showing in the picture. https://prnt.sc/1mo2xeo -
Unhandled Rejection (TypeError): Cannot read property 'value' of undefined
I am working on React js with Django Rest API. When I try to submit form data through api, it showing me the error. I think some null values are going to api and I dont know how to check them. I am new to react.js learning from on tutorial.Can anyone please teach me a way to debug this kind of issues. Unhandled Rejection (TypeError): Cannot read property 'value' of undefined 22 | this.setState({ btnMessage: 1 }); 23 | 24 | var apiHandler = new APIHandler(); > 25 | var response = await apiHandler.saveMedicineData( | ^ 26 | event.target.name.value, 27 | event.target.medical_typ.value, 28 | event.target.buy_price.value, Here is my form code: async formSubmit(event) { event.preventDefault(); this.setState({ btnMessage: 1 }); var apiHandler = new APIHandler(); var response = await apiHandler.saveMedicineData( event.target.name.value, event.target.medical_typ.value, event.target.buy_price.value, event.target.sell_price.value, event.target.c_gst.value, event.target.s_gst.value, event.target.batch_no.value, event.target.shelf_no.value, event.target.expire_date.value, event.target.mfg_date.value, event.target.company_id.value, event.target.description.value, event.target.in_stock_total.value, event.target.qty_in_strip.value, this.state.medicinedetails ); this.setState({ btnMessage: 0 }); this.setState({ errorRes: response.data.error }); this.setState({ errorMessage: response.data.message }); this.setState({ sendData: true }); } Below is the Api Handler: async saveMedicineData( name, medical_typ, buy_price, sell_price, c_gst, s_gst, batch_no, shelf_no, expire_date, mfg_date, company_id, description, in_stock_total, qty_in_strip, medicinedetails ) { await this.checkLogin(); //Wait Until Token Get Updated var response = await Axios.post( Config.medicineApiUrl, { name: … -
App level static files loading in Django but not Project Level
My app-level static files are loading but not project level Whenever I try to access static files via localhost/static/css/... I can only access my app-level static files and not project-level. Here is my settings.py STATICFILES_DIRS = [ os.path.join(BASE_DIR, '/static'), os.path.join(BASE_DIR, '/projects/static'), ] Here is the structure of my file directory structure | db.sqlite3 | manage.py | +---portfolio | | asgi.py | | settings.py | | urls.py | | wsgi.py | | __init__.py | +---projects | | admin.py | | apps.py | | models.py | | tests.py | | urls.py | | views.py | | __init__.py | | | +---static | | | | | +---css | | | projects.css | | | | | \---img | | test-1.jpg | | test-2.jpg | | test-3.jpg | +---static | +---css | | base-template.css | | | \---js +---templates | base.html | projects.html | project_detail.html -
expected str, bytes or os.PathLike object, not QuerySet
I want to extract the file field from my model , and open the file (file is in .pdf format) . but I got this error : expected str, bytes or os.PathLike object, not QuerySet my models.py is : class FileUpload(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True , null=True) file = models.FileField(upload_to='files') def get_absolute_url(self): return reverse('home') my views.py is : class PostDetailView(DetailView): context_object_name = "object_list" template_name = "post_detail.html" def get_object(self, *args,**kwargs): request = self.request pk = self.kwargs.get('pk') instance = FileUpload.objects.filter(id = pk) if instance is None: raise Http404("File Does not EXIST") else: pdfFileObj = open(instance, 'rb') pdfReader = PyPDF2.PdfFileReader(pdfFileObj) print(pdfReader.numPages) pageObj = pdfReader.getPage(0) print(pageObj.extractText()) pdfFileObj.close() return instance Right now I am not using any template . Just want to print the file data inside my terminal . Mean when I refresh the page I got this error . -
Django similar url pattern issue
I am working on a products comparison module and have url patterns like below: path('comparison/<slug:slug1>-vs-<slug:slug2>/', views.compare_two_products, name="compare_two_products"), path('comparison/<slug:slug1>-vs-<slug:slug2>-vs-<slug:slug3>/', views.compare_three_products, name="compare_three_products"), The issue is that Django always matches the first pattern and returns 404 when I try to access the second pattern. However if I comment out the first pattern, then it matches the third pattern just fine. I want to get both the patterns working in the format slug-vs-slug-vs-slug. Any suggestions on what I might be doing wrong ? Thanks in advance. -
id1 - 1, id2 - 2, id3 - 2, id4 - 2, id5 - 3 if this is given then the final list will be id1, id4, id5, id3 and id2 python
i have list of data , I need to send that particular order like this: allready taken id need to move for next like that total list i need work (id1-1 ,id2-2 ,id3-2 then id2 moves to id3 and id2 goes for id3) example : id1 - 1, id2 - 2, id3 - 2, id4 - 2, id5 - 3 if this is given then the final list will be id1, id4, id5, id3 and id2 -
Serializing 3 Interconnected Django relational models
I am trying to write a set of serializers for my models. I want the serializer for the deck to spit out the cards that match the decks ID in the CardToDeck Model and then fetch the card matching the card_id in the Card Model models.py from django.db import models # Create your models here. class CardToDeck(models.Model): deck_id = models.ForeignKey("Deck", related_name="card_to_deck", on_delete=models.CASCADE) card_id = models.ForeignKey("Card", related_name="card_to_deck", on_delete=models.CASCADE) class Card(models.Model): id = models.AutoField(primary_key=True) multiverseid = models.IntegerField(unique=True) # Used to fetch the card from the API name = models.CharField(max_length=145) class Deck(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=145) serializers.py: from .models import * from rest_framework import serializers class CardSerializer(serializers.ModelSerializer): class Meta: model = Card fields = ('id', 'name') class CardToDeckSerializer(serializers.ModelSerializer): class Meta: model = CardToDeck fields = ('deck_id', 'card_id') # Serializer for Deck that grabs the nested model references class DeckSerializer(serializers.ModelSerializer): cards = serializers.PrimaryKeyRelatedField(queryset=CardToDeck.objects.all(), many=True) class Meta: model = Deck depth = 2 fields = ('name', 'cards') What I would like the JSON to look like: { "name": "deckNameGoHere", "cards": [{"id":1, "name":"cardNameGoHere", "quantity":3},{"id":2, "name":"cardNameGoHere", "quantity":2}] } I just spent the last 4 hours trying to figure this out and feel quite dumb, any help would be appreciated. I looked into the docks but … -
Why is requiring login on every page my django app on heroku?
I deployed a django web-app on Heroku. It has some views that require login and others that doesn't. If I set DEBUG = False on settings.py and push to Heroku, then all the URLS with the domain of my app require login. For Example: If I try to access to example.herokuapp.com then it will redirect me to example.herokuapp.com/accounts/login/?next=/ which is fine, beacause example.herokuapp.com require login to display If I try to access to example.herokuapp.com/accounts/signup/ then it will redirect me to example.herokuapp.com/accounts/login/?next=/accounts/signup/ which shouldn't happen, because example.herokuapp.com/accounts/signup/ doesn't require login If I try to access to example.herokuapp.com/blablablabla then it will redirect me to https://cafa.herokuapp.com/accounts/login/?next=/blablablabla which isn't right, because example.herokuapp.com/blablablabla is not even an included url in my app. I'm not sure how to fix this and I haven't find anything useful to guide myself to a solution. If it's necessary that I show part of the code I'll be happy to do it if that helps to find a solution. -
I want to implement an otp module when the user clicks on change number in the edit profile section of a django website. How to go about?
I tried implementing this using 2factor api. Created two html files and one for entering number and second for verifying otp. Changed the views and models files accordingly. -
How do i ensure that a django search form is not empty
I have this blog app and i want that when a user goes to /search, they can be able to search and filter blogs by either the author, title, or blog tags. I've already enabled Django-filter and its working, quite alright but when a user does not input a value and hits the search button, it just shows all the items in the database and i don't want that. i want them to get a flash message saying they need to input at least an item. Here is what my code looks like views.py def search(request): form = SearchForm() context = { 'form': form } return render(request, 'blog/search.html', context) def searchResults(request): blogs = BlogPost.objects.all() blog_filter = BlogPostFilter(request.GET, queryset=blogs) blogs = blog_filter.qs for item in request.GET: if request.GET[item] == '': print('sorry') context = { 'blogs': blogs, } return render(request, 'blog/search_results.html', context) forms.py class SearchForm(ModelForm): author = forms.ModelChoiceField( queryset=UserProfile.objects.all(), label='', required=False, ) title = forms.CharField( label="", required=False, widget=forms.TextInput(attrs={ 'placeholder': 'Title', 'class': 'form-control'}) ) short_description = forms.CharField( label="", required=False, widget=forms.TextInput(attrs={ 'placeholder': 'Short description', 'class': 'form-control'}) ) category = forms.ModelChoiceField( queryset=Category.objects.all(), label='', required=False, ) class Meta: model = BlogPost fields = '__all__' exclude = ['likes', 'related_image', 'date_added', 'content'] filters.py class BlogPostFilter(django_filters.FilterSet): title = CharFilter(field_name='title', … -
Django: How to authenticate a form in class based views
I am new to Django and I have this idea that when I user enters a room(image of the room) a modal popup ask them for a password of that specific room(as there will be other rooms) before they can get inside and see it's contents and the password is created by the admin in the admin site. Now my problem is I've created a password field on my room model, and I've also created a form for it, but I am having a hard time on how to incorporate it in my views.. I have no idea on how to GET the password that admin created and match it with what the user POST as the password. Could someone help me out? My Room model class Room(models.Model): name = models.CharField(max_length=100, unique=True) password = models.CharField(max_length=32, unique=True, null=True) slug = models.SlugField(null=True, blank=True) description = models.TextField(max_length=500,blank=True) def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) super().save(*args, **kwargs) My form class RoomForm(forms.ModelForm): class Meta: Model = Room fields = ['password'] labels = {"password": "Room Password:"} widgets = { 'password':forms.PasswordInput() } My views class RoomListView(FormView, ListView): context_object_name = 'rooms' model = Room template_name = 'mysite/room_list_view.html' form_class = RoomForm -
Django built-in cache or use Redis in the source?
Well currently I am working at a source of django and found this in docker-compose.yml redis: container_name: cache image: redis:alpine ports: - 6379:6379 I was told that they use redis for saving cache. However, as I research django did have built-in catch from this link https://docs.djangoproject.com/en/3.2/topics/cache/ Since, I am beginner, I wonder what is the trade-off between build redisand use built-in catchof django in term of saving Catch. And if it was your case which one is more preferable.