Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I already have a form created in HTML, how can I post the data from this form to the user's account on the Django database?
I am working on the project in which one user can create a quiz on the HTML pages without coding, in an interactive way. This created quiz should be displayed on the screen of another user, who will be attempting the tests. I am using Django framework for backend and I am very new to backend. -
Djangi : django.core.exceptions.FieldError: Cannot resolve keyword 'email' into field
**I Got errors like that, please help me. django.core.exceptions.FieldError: Cannot resolve keyword 'email' into field. Choices are: auth_token, created_at, id, is_verified, nama, order, pengiriman, user, user_id view.py def processOrder(request): id_transaksi = datetime.datetime.now().timestamp() data = json.loads(request.body) if request.user.is_authenticated: customer = request.user.profile order, created = Order.objects.get_or_create(user=customer, selesai=False) else: customer, order = gusetOrder(request, data) total = float(data['form']['total']) order.id_transaksi = id_transaksi if total == order.get_cart_total: order.selesai = True order.save() if order.shipping == True: Pengiriman.objects.create( user=customer, order=order, alamat=data['shipping']['address'], kota =data['shipping']['city'], provinsi=data['shipping']['state'], kode=data['shipping']['zipcode'], ) return JsonResponse('Payment complete', safe=False) checkout.html function submitFormData(){ console.log('Payment button clicked') var userFormData = { 'name':null, 'email':null, 'total':total, } var shippingInfo = { 'address':null, 'city':null, 'state':null, 'zipcode':null, } if (shipping != 'False'){ shippingInfo.address = form.address.value shippingInfo.city = form.city.value shippingInfo.state = form.state.value shippingInfo.zipcode = form.zipcode.value } if (userau == 'False'){ userFormData.name = form.name.value userFormData.email = form.email.value } console.log('Shipping Info:', shippingInfo) console.log('User Info:', userFormData) var url = "/process_Order" fetch(url, { method:'POST', headers:{ 'Content-Type':'applicaiton/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'form':userFormData, 'shipping':shippingInfo}), }) .then((response) => response.json()) .then((data) => { console.log('Success:', data); alert('Transaction completed'); cart = {} document.cookie ='cart=' + JSON.stringify(cart) + ";domain=;path=/" window.location.href = "{% url 'store' %}" }) } base.html function getToken(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for … -
Relation between two models in Django
It seems like a trivial question but I am new to Django. I have two models user and competition. The user can create and join one or many competition. How to specify this relation as the user can be the owner of competition/s and can be a participant in one or more competition. -
data encryption on amazon Aurora and django system
I am using amazon aurora and django. Now, thinking about using RDS encryption Hoever while reading documents, a few questions come up to me. My final goal is encrypting data itself, even mysql root user can not check the data. This doesn't encrypt the database data itself, so if DB user/password is leaked, the data could be stolen? Is there any good way to encrypt the data in database? even root mysql user can not check the data. I am using django, It is enough that only django can encode-decode the data. I should use some django library not database itself? or database has some structure for this purpose? -
Django still working fine even when DEBUG=False in settings.py
In settings.py, DEBUG set to True. But when we move it to the production we should be setting DEBUG=False. So in my local environment itself, I have changed to DEBUG=False. But still my application is working fine even with this settings. Usually when we changed DEBUG to false we should be getting some issues like 500 or 404 error something like that , but in my case its not like that. I have referred this """ https://stackoverflow.com/questions/38617046/django-debug-false-still-runs-in-debug-mode/47266619""" but it did not help much for me. Please let me know if i misunderstood or missed something. Below is the small snippet of code i have in settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]' DEBUG = False ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'MyApp', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] 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', ] Please let me know if i need to provide anymore details. -
DJANGO : checkout:293 POST http://127.0.0.1:8000/process_Order 403 (Forbidden)
```Help errorrrhi [enter image description here][1]I got error like that please help me[ def processOrder(request): id_transaksi = datetime.datetime.now().timestamp() data = json.loads(request.body) if request.user.is_authenticated: customer = request.user.profile order, created = Order.objects.get_or_create(user=customer, selesai=False) else: customer, order = gusetOrder(request, data) total = float(data['form']['total']) order.id_transaksi = id_transaksi if total == order.get_cart_total: order.selesai = True order.save() if order.shipping == True: Pengiriman.objects.create( user=customer, order=order, alamat=data['shipping']['address'], kota =data['shipping']['city'], provinsi=data['shipping']['state'], kode=data['shipping']['zipcode'], ) return JsonResponse('Payment complete', safe=False) function submitFormData(){ console.log('Payment button clicked') var userFormData = { 'name':null, 'email':null, 'total':total, } var shippingInfo = { 'address':null, 'city':null, 'state':null, 'zipcode':null, } if (shipping != 'False'){ shippingInfo.address = form.address.value shippingInfo.city = form.city.value shippingInfo.state = form.state.value shippingInfo.zipcode = form.zipcode.value } if (userau == 'False'){ userFormData.name = form.name.value userFormData.email = form.email.value } console.log('Shipping Info:', shippingInfo) console.log('User Info:', userFormData) var url = "/process_Order" fetch(url, { method:'POST', headers:{ 'Content-Type':'applicaiton/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'form':userFormData, 'shipping':shippingInfo}), }) .then((response) => response.json()) .then((data) => { console.log('Success:', data); alert('Transaction completed'); cart = {} document.cookie ='cart=' + JSON.stringify(cart) + ";domain=;path=/" window.location.href = "{% url 'store' %}" }) } function getToken(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this … -
Can I access Django Admin Site using deployed URL?
I just deploy my first Django Rest Framework into Heroku. Site URL is https://mysite.herokuapp.com/ I already can access admin site using http://127.0.0.1:8000/ through created superuser account. But How I am gonna access the admin site using the deployed url?. Thanks -
Django Migrations with multiple legacy databases with multiple tables in same app
Need help with migrations of already existing databases (MySQL) with lots of tables and data. These databases were manually being updated from CLI but now they need a web interface with all the stats and collaborations etc. The tables are connected between DBs and let's say there are 10tables in db1, 5 tables in db2. I have two apps 'login' and 'main'. Login: The 'default' database is being used for authentication/login. model.py is in app 'login'. Db setting for 'default' is in settings.py This is working fine. Initial migrations worked. Main: Second app, 'main', is suppose to connect to two databases, db1, db2 and fetch/update/remove data to already existing data through views. I added the mysql connector to settings.py with database parameters and it's able to connect via dbshell. Connection is working. Using 'inspectdb' I got the two models, one from each database (m1.py, m2.py). The 'models.py' in main app is empty for now. 'managed' in meta is False for all classes generated via inspectdb. Q: How to put all the tables/classes from both the databases (m1, m2) into models.py and do migrations? If I do migrate it can affect the 'default' (please correct me). If I specify the --database … -
Python/Docker - Method delete not allowed Django
I am trying to run a program using docker that will allow me to destroy requests by using a program called PostMan to do this I have set up a class named ProductViewSet which will allow me to delete a query. But when I run docker-compose up in my Visual Studio Terminal and try to run a DELETE query through PostMan it gives me an error in PostMan that says "detail": method "DELETE" not allowed. I have tried to use the @action function to try and link the destroy function from my views.py to my urls.py in the same folder using this answer Method Delete Not Allowed - destroy() method Django, I have also tried to just use my main function Product and use a router as seen in this answer "detail": "method \delete\ not allowed" django but both of these answers do not help me at all. Here is my error that I am getting in PostMan and in my Visual Studio Terminal: Postman: { "detail": "Method \"DELETE\" not allowed." } Visual Studio Terminal: backend_1 | 172.19.0.1 - - [16/Mar/2022 00:58:14] "DELETE /api/products HTTP/1.1" 405 - Here are my requirements.txt, Dockerfile, docker-compose.yml, and views.py files respectivly: requirements.txt: Django==3.1.3 djangorestframework==3.12.2 … -
Delete db.sqlite via terminal (Django)
I'm currently deploying a project to Heroku, however it returns me the following error: ValueError: Related model 'store.user' cannot be resolved. But there is a way to avoid such error locally. You simply do: py manage.py migrate store And then py manage.py migrate In other words, if I migrate separetely, I won't face such error. However, Heroku migrates all together, then the deploy fails because of this error. If I proceed locally as Heroku does, i.e. run py manage.py migrate I can effortlessly click on and delete the db.sqlite3 file and makemigrations and migrate separetely. Then the issue would be resolved. However, that's not possible when deploying to Heroku. Thus, how can I delete this file only via terminal? I have been searching, but people only say you click on the file and the delete it, which for me it is not possible. Thanks -
How to add source code option to Rick text field in django
I want to add the source code functionality to my rich text field in Django and I don't know how to go about it. I already know how to install and setup rich text field but how to add the source code functionality is what I need -
Call html file in iframe with javascript, in a django project
I want to open a html file of a Django application, in a javascript. document.getElementById("iframe_id").src = "{% url 'application/file.html' %}"; I receive the error : Exception Type: NoReverseMatch Exception Value: Reverse for 'application/file.html' not found. 'application/file.html' is not a valid view function or pattern name. -
DRF DefaultRouter pk/slug
I noticed that sites such as SO and Reddit use <basename>/<pk>/<slug>/ for the detail view of posts, which makes me think that this should be the standard. Is there a way to accomplish this in drf using routers and ModelViewset? example of ModelViewset: class PostViewSet(viewsets.ModelViewSet): ... lookup_fields = ['pk', 'slug'] example of DefaultRouter : router = DefaultRouter() router.register('posts', PostViewSet, basename='post') app_name = 'api' urlpatterns = [ path('', include(router.urls)), ] URL patterns: /api/post/ api.views.PostViewSet post-list /api/post/<pk>/<slug>/ api.views.PostViewSet api:post-detail /api/post/<pk>/<slug>\.<format>/ api.views.PostViewSet api:post-detail /api/post\.<format>/ api.views.PostViewSet api:post-list -
Authentication credentials weere not provided when signing up
Building Django APIs to help me handle both the signup and login process for my React app. I am able to successfully login (get an access and refresh token from Django upon login), but having difficulties connecting my React signup process to Django to create a new user. This is the error I am getting on my console: POST http://127.0.0.1:8000/users/ 401 (Unauthorized) onSubmit @ Signup.js:32 and on my network: Authentication credentials were not provided. This is what I have in my serializers.py from django.contrib.auth.models import User from rest_framework import serializers class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'email', 'password'] extra_kwargs = { 'password': {'write_only':True}, } def create(self,validated_data): user = User.objects.create_user(validated_data['username'], password=validated_data['password'], email=validated_data['email']) return user class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' class UserSerializerWithToken(serializers.ModelSerializer): token = serializers.SerializerMethodField() password = serializers.CharField(write_only=True) class PasswordSerializer(serializers.Serializer): old_password = serializers.CharField(required=True) new_password = serializers.CharField(required=True) accounts.urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('signup.urls')), ] signup.urls.py from django.contrib import admin from django.urls import path, include from rest_framework import routers from . import views from rest_framework_simplejwt.views import (TokenObtainPairView, TokenRefreshView, TokenVerifyView) from .api import RegisterApi router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) urlpatterns = [ path('', include(router.urls)), path('admin/', … -
Posting images to userProfile django
I was able to automaticcaly create a userProfile everytime a user is created but I want to be able to modify somefields in the userprofile. So my Model.py def upload_path(instance,filename): return 'users/avatars/{0}/{1}'.format(instance.user.username, filename) class UserProfile(models.Model): user= models.OneToOneField(User,on_delete=models.CASCADE, related_name='userprofile') Profileimage= models.ImageField(upload_to=upload_path, blank=True, null=True, default='user/avatar.jpeg') def __str__(self): return self.user.username @ receiver(post_save,sender=User) def create_user_profile(sender,instance,created,**kwargs): if created: UserProfile.objects.create(user=instance) My Serializer.py class UserSerializer(serializers.ModelSerializer): #ProfileImage=serializers.ImageField(allow_null=True, use_url=True) class Meta: model = User fields =['id', 'username','password','email'] extra_kwargs={'password':{'write_only':True, 'required':True}} def create(self,validated_data): user =User.objects.create_user(**validated_data) Token.objects.create(user=user) return user class UserProfileSerializer(serializers.ModelSerializer): user = serializers.StringRelatedField(read_only=True) class Meta: model =models.UserProfile #lookup_field = 'username' fields= ['id','user','Profileimage'] My view.py class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer lookup_field = 'username' class UserProfileViewSet(viewsets.ModelViewSet): queryset = UserProfile.objects.all() serializer_class = UserProfileSerializer lookup_field = "username" The page looks like : enter image description here So how can I modify the picture of the user, I tried to add forms but I couldn't match the username, sometime I guet the error Userprofile has no user. Anyhelp? -
Django no such table: Fligts_country when trying to migrate app model using Foreign key
Intro Hi, first off thanks in advanced for helping. I am learning the Django framework and I am having trouble trying to create a simple relation between two tables in my model. I am running django and mysql in docker in two separate containers, created by a docker-compose file (code is down below) and so far I have not been able to create the tables (migrations). Problem When I execute the command: python manage.py migrate --database=mariadb I get as a result: django.db.utils.OperationalError: no such table: Fligts_country In other posts similar to this one (Django - no such table exception for example) I see that a common solution is to remove the pycache folder and migrations as well, but this is not working for me and I have been strugling for some time now... Desired Solution I need the tables to be created in the database, but most importantly I want to know what is exactly wrong with my code. I assume that there is something that I am missing about Foreign keys. My code so far Docker-compose.yml version: '3' services: travel-crawler: restart: always container_name : travel-crawler build: ./Crawler tty: true ports: - '9005:8080' volumes: - type: bind source : E:\python-code\Traveler\Crawler … -
Passing context to serializer from Viewset
I have Viewset with get_serializer_context method class UserRetrieveView(generics.RetrieveAPIView): queryset = User.objects.all() permission_classes = (AllowAny,) serializer_class = UserProfilePageSerializer def get_serializer_context(self): context = super(UserRetrieveView, self).get_serializer_context() context.update({'room' : self.get_object().room_set.all()}) print(context['room']) return context And now I want to put this context to my serializer : class UserProfilePageSerializer(ModelSerializer): class Meta: model = User fields = ['id', 'username', 'name','bio'] Honestly I have no idea how to do this. I would really appreciate any help or even some clue -
Django passing data through the url, not finding page in url patterns
I'm trying to pass an object's id through the url, but its not able to find the page even after it tries the path when it goes through its patterns Error: Using the URLconf defined in GroomingService.urls, Django tried these URL patterns, in this order: admin/ [name='Home'] appointment-Maker/ account/ admin-home view_appointment/<id>/ login/ [name='Login Page'] registration/ [name='Registration Page'] logout [name='Logout Page'] The current path, adminview_appointment/21/, didn’t match any of these. GroomingService.urls #urls urlpatterns = [ path('admin/', admin.site.urls), path('', Home_view, name="Home"), path('appointment-Maker/', include('appointmentApp.urls')), path('account/', include('accountApp.urls')), path('admin-home', include('adminApp.urls')), path('view_appointment/<id>/', viewAppointment_view), #this is the page it is not finding path('login/', Login_view, name='Login Page'), path('registration/', Registration_view, name='Registration Page'), path('logout', Logout_view, name='Logout Page') ] adminApp/views.py viewAppointment_view def viewAppointment_view(request, id): appointments = Appointment.objects.get(id = id) context = { 'appointments' : appointments } return render(request, "admin_templates/viewappointment.html", context) templates/admin_templates viewappointment.html {% extends 'base.html' %} {% block content %} <a>appointment view</a> {% endblock %} templates/admin_templates adminhome.html (the link is clicked through this page) {% extends 'base.html' %} {% block content %} <a>this is the admin page</a> <br> {% for a in appointments %} <a href="adminview_appointment/{{a.id}}/">Client name:{{a.client_dog_name}}</a><br> {% comment %} this is the link that is clicked {% endcomment %} {% endfor %} <br> <a>find month</a> <form method="POST"> {% csrf_token %} … -
How to iterate through queryset and get value Django
I wanna do a simple recommendation system based on users' Animals that they added. I want to show only products of a category, that's been mapped in "zwierzeta" dictionary. So basically if user has chosen that he has a horse (which is id 1, i want to show only products that have category 4) Also if user has more than 1 animals, i want to show them randomly from list of categories id. The logic seems to be fine, im just new at django and i have no idea how to actually iterate through the querysets and how to get a value(animal) from a particular queryset. The get method doesnt work. Do you have any idea how to get a particular value from a queryset? class MyAnimal(models.Model): name = models.CharField(max_length=256) animal = models.ForeignKey(Animal, on_delete=models.CASCADE, null=False) class ProductInStore(models.Model): product = models.ForeignKey('Product', on_delete=models.CASCADE) class Product(models.Model): product_category = models.ManyToManyField(EcommerceProductCategory) def list(self, request): zwierzeta = {1 : 4, 6: 5, 8: 6, 9: 6, 4: 3} qs = MyAnimal.objects.filter(user=self.request.user) #checking if there is an animal with user == self.request.user if qs: if len(qs)==1: # if user has only 1 animal, get that animals race and if compare it with the dictionary to get product__product_category … -
heroku error - template does not exist at / web/index.html
i have been stumped for days, trying to figure this out. Ive looked at every stack overflow post relating to this and now I'm resorting to making my own. all the other posts say the error has something to do with the settings.py file so here it is: from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent.parent ALLOWED_HOSTS = [ '127.0.0.1', 'd1sbot.herokuapp.com', ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'web', ] 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', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'botfiles.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'botfiles.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/4.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.0/howto/static-files/ os.path.join(os.path.dirname(__file__) ,'../templates').replace('\\','/') STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) # … -
How to get data from django orm inside an asynchronous function?
I need to retrieve data from the database inside an asynchronous function. If I retrieve only one object by executing e.g: users = await sync_to_async(Creators.objects.first)() everything works as it should. But if the response contains multiple objects, I get an error. @sync_to_async def get_creators(): return Creators.objects.all() async def CreateBotAll(): users = await get_creators() for user in users: print(user) Tracing: Traceback (most recent call last): File "/home/django/django_venv/lib/python3.8/site- packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/django/django_venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/django/django_venv/src/reseller/views.py", line 29, in test asyncio.run(TgAssistant.CreateBotAll()) File "/usr/lib/python3.8/asyncio/runners.py", line 44, in run return loop.run_until_complete(main) File "/usr/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete return future.result() File "/home/django/django_venv/src/reseller/TgAssistant.py", line 84, in CreateBotAll for user in users: File "/home/django/django_venv/lib/python3.8/site-packages/django/db/models/query.py", line 280, in __iter__ self._fetch_all() File "/home/django/django_venv/lib/python3.8/site-packages/django/db/models/query.py", line 1324, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/home/django/django_venv/lib/python3.8/site-packages/django/db/models/query.py", line 51, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/home/django/django_venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1173, in execute_sql cursor = self.connection.cursor() File "/home/django/django_venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 31, in inner raise SynchronousOnlyOperation(message) django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. -
django show last 3 char of string in admin fields
database | id | salary_number | | --- | ------------- | | 1 | 1042 | models.py class user(AbstractUser): salary_number = models.CharField(max_length=4, unique=True, null=True, blank=True) def __str__(self): return f'{self.salary_number[-3:]}' admin.py class UserAdmin(admin.ModelAdmin): fields = ('salary_number[-3:]',) I would like to show Salary number: 042 in admin fields instead of 1042. Is it possible? -
creating/deleting folders in runtime using heroku/django
I have developed a Django app where I am uploading a file, doing some processing using a project folder name media. Process: user uploads a csv file, python code treats the csv data by creating temp folders in Media folder. After processing is complete, these temp folders are deleted and processed data is downloaded through browser. I am using the below lines of code to make and delete temp file after processing temp = 'media/temp3' os.mkdir(temp) shutil.copyfile('media/' + file_name, temp + '/' + file_name) shutil.rmtree(temp, ignore_errors=True) To set the media root, I used the below lines in settings.py which I am sure I am not using in other parts of the code. MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = "/media/" Everything works fine when I run the app on local host. but as soon as i deployed it to heroku, it seems like these folders were not created/not found. I am looking for: Either a solution to create, read and delete folders/files in runtime using heroku, or a better way to manage files/folders in runtime. -
How to add a searchable text field to select a foreign key item in Django form?
I have a filter form as you can see in the screenshot. I would like to add a searchable field(in the red area) so users can filter the campaign naming tool object instead of scrolling. Any help is appreciated. My filter class class UserInsertionOrderFilter(django_filters.FilterSet): start_date = django_filters.DateFilter(widget=DateInput) end_date = django_filters.DateFilter(widget=DateInput) class Meta: model = UserInsertionOrder fields = [ 'campaign_naming_tool', 'start_date', 'end_date' ] My filter form -
Django request for CAC (common access card)
I am currently running my Django application on an Apache v2.4.5.2 server. When the user hits initial page (i.e. www.djangoApp.com) they are prompted to insert their CAC and PIN. Once complete, the PIN entry pop-up goes away and the user is directed to the landing page. The issue I'm having is figuring out how to identify the user based on the HTTP response received from the external source (GCDS). In the server logs, I can see the request information, but I am unsure how to view that request in Django views. I tried to comment out all middleware so that the request would make it through, but that doesn't work. Does Apache block certain HTTP Requests? Is there somewhere I need to allow external requests? The only request I'm getting is: {'GATEWAY_INTERFACE': 'CGI/1.1', 'SERVER_PROTOCOL': 'HTTP/1.1', 'REQUEST_METHOD': 'GET', 'QUERY_STRING': '', 'REQUEST_URI': '/', 'SCRIPT_NAME': '', 'PATH_INFO': '/', 'PATH_TRANSLATED': '\DjangoWebProject1\\wsgi.py\\', 'HTTP_HOST': 'glen', 'HTTP_CACHE_CONTROL': 'max-age=0', 'HTTP_SEC_CH_UA': '" Not A;Brand";v="99", "Chromium";v="99", "Google Chrome";v="99"', 'HTTP_SEC_CH_UA_MOBILE': '?0', 'HTTP_SEC_CH_UA_PLATFORM': '"Windows"', 'HTTP_UPGRADE_INSECURE_REQUESTS': '1', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36', 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'HTTP_SEC_FETCH_SITE': 'none', 'HTTP_SEC_FETCH_MODE': 'navigate', 'HTTP_SEC_FETCH_USER': '?1', 'HTTP_SEC_FETCH_DEST': 'document', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate, br', 'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.9', 'HTTP_COOKIE': 'csrftoken=Nd3ggEPk0vqYJwZKOVZZoZtUqZWXs155Y6V1q', 'HTTP_X_FORWARDED_FOR': '128.202.106.24', 'HTTP_X_FORWARDED_HOST': 'glen', 'HTTP_X_FORWARDED_SERVER': …