Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django implement installable plugins at runtime
I want to made Django app that allows creation and then installation of plugins, or modules, for it, somewhat like you can do in CMS. Creator of plugin should define models, some configuration settings and handler functions for actions. Plugin will provide only REST api, so no templates required. Plugins must be installed at runtime - creator fills form, attaches archive with code, and plugin gets installed and activated. Unfortunately, my understanding of Django internals is way too low for this task. The most tricky part is runtime installation. There is answer how to install django app at runtime, but it feels hacky. Also, there is lib called django-pluggins, but it works with older version of Django and seems unmaintained. -
Enable support for django tags inside js
i currently have to use django template tags inside js. Example: <script> {% for od in object %} [convertDate("{{ od.date_recorded|date:'Y-m-d' }}"), {{ od.value_recorded }}], {% endfor %} </script> visual studio code shows error, is there a way to enable this support? -
While getting employee duration from joining to date.today() in Django query using F() objects and DurationField(), I am getting negative output
I am writing a query to get duration between 2 date fields. One is from django model (dateField) and other is simply datetime.date.today(). I have used F() objects for model column value to avoid memory usage. def duration(self): emp_duration = Employee.objects.values('empName', 'empJoining').annotate( duration=(datetime.date.today() - F('empJoining')) ) return HttpResponse(emp_duration) Output: {'empName': 'xyz', 'empJoining': datetime.date(2003, 1, 21), 'duration': -20028098.0} {'empName': 'Amna', 'empJoining': datetime.date(2022, 8, 9), 'duration': -20218786.0} {'empName': 'abc', 'empJoining': datetime.date(2022, 7, 17), 'duration': -20218694.0} Have a look at duration field. I dont understand why its in negative. Then I used ExpressionWrapper with outputfield as DurationField(). Since F() objects needs ExpressionWrapper to define outputFields. def duration(self): emp_duration = Employee.objects.values('empName', 'empJoining').annotate( duration=ExpressionWrapper( (datetime.date.today() - F('empJoining')), output_field=DurationField() ) ) return HttpResponse(emp_duration) Output: {'empName': 'xyz', 'empJoining': datetime.date(2003, 1, 21), 'duration': datetime.timedelta(days=-1, seconds=86379, microseconds=971902)} {'empName': 'Amna', 'empJoining': datetime.date(2022, 8, 9), 'duration': datetime.timedelta(days=-1, seconds=86379, microseconds=781214)} {'empName': 'abc', 'empJoining': datetime.date(2022, 7, 17), 'duration': datetime.timedelta(days=-1, seconds=86379, microseconds=781306)} Days difference is same in each row and not the right answer though. The substraction is not correct. What is the issue, if someone can give me better approach or point out what am I missing here, that will be a favor. Thanks -
Getting {"error": "invalid_grant" } in Django OAUTH when trying to generate a token using AUTHORIZATION CODE FLOW
I'm trying to access token using authorization code flow. Following documentation at Django OAuth Here's my code that's making the post request: curl --location --request POST 'http://127.0.0.1:8000/o/token/' \ --header 'Content-Type: application/x-www-form-urlencoded' \ --header 'Cache-Control: no-cache' \ --header 'Accept: application/json' \ --data-urlencode 'client_id=ngta3GGa3jP6Rmv5Tspj97Bk4aiitHgv1EQilCDS' \ --data-urlencode 'client_secret=zLwMyuXg7WCSFwUDYBxFP3QxHh5mF6xM2hBsKyvRbypac5lV7fl2NoFeeDG3afWWxLedA7qtzD2Mvf68qyBra3A4iUXXlDXJO4LvxuZv4UULU6NLWlObpD0ylQSXbwZD' \ --data-urlencode 'code=q4NfBMbyTNbcIQZ4j7SfgMWL898psv' \ --data-urlencode 'redirect_uri=http://localhost:8000/no/callback/' \ --data-urlencode 'code_verifier=b'\''SlJDWEgyRzNYMks0RTVQVDlRVkFaOFdDUkxHV1A3QURMTjNITFdaMTBLU0tWQkkzMUVWVEZFU0k='\''' \ --data-urlencode 'grant_type=authorization_code' I'm expecting to get an access token when I make the post request, but I'm getting this error: { "error": "invalid_grant" } -
How to print errors in console while Object.DoesNotExist
I have 2 files with functions and im trying to show my errors in celery worker console but i have an error: "DETAIL: Key ("GUID")=(#some-guid) already exists." I have try except in the second "create_section" file but for some reason its not working and i got an error in console, how can i handle that? Return or raise wont help me bcs i need code to work after this error Btw: if i just put my create_section code in create_obj file it works fine create_obj.py: for item in response.json(): object_list_json = json.dumps(item) object_list = ObjectListSerializer.parse_raw(object_list_json) section_list = object_list.Sections try: object_list_model = ObjectList.objects.get(GUID=object_list.ObjectGUID) object_list_model.name = object_list.ObjectName create_section(section_list, object_list_model, SectionList) except ObjectList.DoesNotExist as e: print(e) object_list_model = ObjectList.objects.create(GUID=object_list.ObjectGUID, name=object_list.ObjectName) create_section(section_list, object_list_model, SectionList) create_section.py: blank_section_list = [] for section in section_list: try: blank_section_list.append(SectionList.objects.get(GUID=section.SectionGUID)) continue except SectionList.DoesNotExist as error: print(error) SectionList.objects.create(GUID=section.SectionGUID, name=section.SectionName, details=section.DetailedSectionName, object_list=object_list_model) object_list_model.section_list.set(blank_section_list) object_list_model.save() -
How do you conditionally display/hide one of two forms with a live search in Django?
I have two forms: from django import forms from .models import Entity, Quote class EntityForm(forms.ModelForm): class Meta: model = Entity fields = ['name', 'website', 'contact'] class QuoteForm(forms.ModelForm): class Meta: model = Quote fields = ['entity', 'text', 'notes'] Initially on page load only the entity name field is displayed along with the whole quote form. The website and contact fields should not be displayed. The user fills in the entity name field. We do a live search to get all values in the entity model that are similar to help them fill in the form. If no results are returned from their input text, the website and contact fields should now be displayed. The live search functionality is fairly simple to implement, however I'm struggling with the hide/unhide functionality and could use some help. The page initially loads the quote text and I'm not sure why. Similarly, when I fill in the entity field with strings I know that aren't in the database there's no hide/unhide toggle. <form> <label for="entity-name">Entity Name:</label> <input type="text" id="entity-name" name="entity-name" onkeyup="searchEntities()"> <div id="search_results"></div> </form> <form id="quote-form"> <div class="form-group"> <label for="quote-text">Quote Text:</label> <textarea class="form-control" id="quote-text" name="quote-text" rows="3"></textarea> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> <script> function searchEntities() { … -
How to reduce more `SELECT` queries which are already reduced by "prefetch_related()"?
I have Country, State and City models which are chained by foreign keys as shown below: class Country(models.Model): name = models.CharField(max_length=20) class State(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(max_length=20) class City(models.Model): state = models.ForeignKey(State, on_delete=models.CASCADE) name = models.CharField(max_length=20) Then, I iterate Country and State models with prefetch_related() as shown below: for country_obj in Country.objects.prefetch_related("state_set").all(): for state_obj in country_obj.state_set.all(): print(country_obj, state_obj) Then, 2 SELECT queries are run as shown below. *I use PostgreSQL and these below are the query logs of PostgreSQL and you can see my answer explaining how to enable and disable the query logs on PostgreSQL: Next, I iterate Country, State and City models with prefetch_related() as shown below: for country_obj in Country.objects.prefetch_related("state_set__city_set").all(): for state_obj in country_obj.state_set.all(): for city_obj in state_obj.city_set.all(): print(country_obj, state_obj, city_obj) Then, 3 SELECT queries are run as shown below: Now, can I reduce 3 SELECT queries to 2 SELECT queries or less? -
How to better control the output location of files produced by rollup
I have the following source directory structure: -- browser/ client.html client.js When I run rollup it produces: -- dist/ browser/ client.html assets/ client-7878f.js I'd like it to output: -- dist/ client.html assets/ client-7878f.js How would one achieve that? My rollup options are: { input: 'browser/client.html', }, -
Generating forms based on user choices in Django
I am working on a Django project whose purpose is to allow the user to fill in some forms. In some of these forms, the user must make a choice between several options and, based on the choice made, a particular form must be generated. At the end of all these forms, the data entered must be used to write a pdf file. As for the functionality related to generating the pdf, what I'm interested in for the purposes of the question is the use of data entered in one view in another view using them as context. Here's what I tried to do. First of all I created some forms in forms.py: class ChoiceForm(forms.Form): CHOICES = [ ('1', 'Choice-One'), ('2', 'Choice Two'), ] choice = forms.ChoiceField(choices=CHOICES) class ChoiceOneForm(forms.Form): name_one = forms.CharField(max_length=200) class ChoiceTwoForm(forms.Form): name_two = forms.CharField(max_length=200) Then I created this view in views.py: def contact(request): if request.method == 'POST': num_people = int(request.POST.get('num_people')) people_formset = [forms.ChoiceForm() for i in range(num_people)] return render(request, 'home.html', {'people_formset': people_formset}) else: return render(request, 'home.html') def generate_pdf(request): context = {} return render(request, 'pdf.html', context) And finally I have this HTML file called 'home.html': <h1>Contact</h1> <form method="post"> {% csrf_token %} People number: <input type="number" name="num_people" required> <input … -
Upload Issue - No Resized Images Generated -django-avatar=5.0.0
I am using django-avatar=5.0.0 on django=1.11.4 and pillow=4.2.1. When i try to upload a new avatar, it saves it in the database but the resized image and folder is created for .jpg and .jpeg file but not for.png file. This is the image source the template is looking for but it's not created: <img src="/media/avatars/user/resized/80/9919.png" alt="Avatar object" width="80" height="80"> But for jpeg and jpg file format, the image is retrived from library: <img src="/media/avatars/user/resized/80/9919.jpeg" alt="Avatar object" width="80" height="80"> -
How to return correct model fields in serializer?
I am implementing a search bar that returns the users and the posts. I am able to return the data but when i clear the search bar i get the error returned: AttributeError: Got AttributeError when attempting to get a value for field username on serializer SearchUserSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Post instance. Original exception text was: 'Post' object has no attribute 'username'. My Models: class User(AbstractUser): avi_pic = models.ImageField( max_length=400, null=True, blank=True, upload_to='images') name = models.CharField(max_length=50, blank=True, null=True) username = models.CharField(max_length=30, unique=True) class Playlist(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, default=None ) cover = models.CharField(max_length=300, default='', blank=True) title = models.CharField(max_length=300, default='', blank=True) date = models.DateTimeField(editable=False, auto_now_add=True) My Serializers: class SearchPostSerializer(serializers.ModelSerializer): username = serializers.SerializerMethodField() class Meta: model = Post fields = ('id', title', 'user', 'username', 'cover') def get_username(self, post): return post.user.username class SearchUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'name', 'username', 'avi_pic') and my Views.py: class SearchView(generics.ListAPIView): def get_serializer_class(self): queryset = self.get_queryset() if len(queryset) == 0: return None if isinstance(queryset[0], User): return SearchUserSerializer elif isinstance(queryset[0], Post): return SearchPostSerializer else: return None def get_queryset(self): query = self.request.query_params.get('q', None) if query is not None: queryset_users = User.objects.filter( Q(name__icontains=query) | … -
How to avoid excessive logging by autoreload in django rest framework?
currently I am using logging from django rest framework.But I am getting excessive logging by autoreload. I want to avoid excessive logging of autoreload. -
Django application running on top of Serverless + Lambda + API Gateway HTTP API is rewriting links to be prefixed with default
My Django Application (Largely REST Framework based) is currently producing URLs on the admin page that don't resolve. The expected result is that the Django Admin's login prompt submits the form with a POST to /admin/login. The resultant URL passed by as the form submission URL by Django is /$default/admin/login and that returns a 404 with the even more obtuse /$default/$default/admin/login/. I'm presuming I have some sort of misconfiguration in either my Django configuration or serverless.yml. As per the following serverless.yml I'm using API Gateway V2, Django through WSGI, and Lambda functions. service: api app: api org: myapp frameworkVersion: '3' provider: name: aws runtime: python3.8 functions: serve: handler: wsgi_handler.handler timeout: 20 environment: DB_NAME: ${param:db_name} DB_PASSWORD: ${param:db_password} DB_USER: ${param:db_user} DB_PORT: ${param:db_port} DB_HOST: ${param:db_host} events: - httpApi: "*" migration: handler: migrate.handler timeout: 60 environment: DB_NAME: ${param:db_name} DB_PASSWORD: ${param:db_password} DB_USER: ${param:db_user} DB_PORT: ${param:db_port} DB_HOST: ${param:db_host} custom: wsgi: app: myapp.wsgi.application plugins: - serverless-python-requirements - serverless-wsgi My URLs are pretty standard: from django.contrib import admin from django.urls import path, include from rest_framework.schemas import get_schema_view schema_view = get_schema_view( title="MyApp", description="MyApp Universal API", version="1.0.0", ) urlpatterns = [ path("admin/", admin.site.urls), path("user/", include("myapp.core.urls"), name="user"), path("openapi", schema_view, name="openapi-schema"), ] My configuration is even more standard: import os from pathlib … -
How to upload react build folder to my remote server?
I'm trying to deploy my react build folder to my server. I'm using index.html and static that configured in my settings.py file to do that. (https://create-react-app.dev/docs/deployment/) Since my backend is running on Ubuntu, I can't just copy from my Windows side and paste it. For now, I uploaded my build folder to my Google Drive and I download it on Ubuntu. But I still can't just copy and paste it on my PyCharm IDE, I can only copy the content in each file and then create a new file ony my server and paste the content to the file. This is just so time-consuming. Is there any better way to do this? Thank you. -
How do I handle sending iOS push notifications if my iOS app back end is in python?
I had a question which I have done a lot of googling on but still couldn't find a suitable answer. I am building my iOS app's back end using django rest framework and what I wanted to know since I am new to iOS is how would notifications show on a user's iphone when lets say a model is changed or something or for example if I make a simple GET request then how does a notification get put out on my iOS app? regards and thanks in advance! Tried googling Tried googling and tried googling -
IntegrityError Django ForeignKey sets to none
I've been having an issue with setting the ForeignKey in one of my model fields for the author variable. See below: class BugTracker(models.Model): project_number= models.IntegerField(primary_key=True) assignee= models.ForeignKey(Developer, on_delete=models.CASCADE) priority = models.CharField(max_length=10, choices=priority_choices) summary=models.TextField() status= models.CharField(max_length=20, choices=progress) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created_at=models.DateTimeField(default=timezone.now) updated_at=models.DateTimeField(auto_now=True) def __str__(self): return self.summary def get_absolute_url(self): return reverse("bug_list") "IntegrityError at /projects/create/ NOT NULL constraint failed: core_bugtracker.author_id Request Method: POST Request URL: http://127.0.0.1:8000/projects/create/ Django Version: 4.1.5 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: core_bugtracker.author_id" As soon as I add "null=True" to the ForeignKey Field, it works and I don't get an error, but the template shows my variable ({bug.author}} equal to "None" regardless of who I'm signed in as. I tried deleting my database and migration files multiple times, but it still doesn't work. Any help would be appreciated here -
How to get request value in another class in django?
It's an example that's as similar as possible, and it's not exactly the same as the actual code. But I believe it's easy to understand. class Fruits: ... def get_sample_data(self, df): ... data = { 'put_file_attachment': >here<, } ... class DataInputForm(forms.Form): attachment = forms.FileField() class MyView(FormView): template_name = 'view.html' form_class = DataInputForm def get_success_url(self): return str( reverse_lazy("milk") ) def post(self, request, *args, **kwargs): get_file = request.FILES.get('attachment') ... k = Fruits() k.load_data() return self.render_to_response(context) I would like to bring the attachment(In fact, get_file) that the user attached to the web class Fruits's >here< In other words, I would like to save the file(get_file) in DB column (put_file_attachment) by the user's attachment. How can I get a value passed to a request from another class to another class? I tried to get 'get_file' by creating a MyView object in the Fruit class, but it doesn't work. Is that possible in this structure or Am I not understanding the concept of request?? -
Trying to configure HTTPS on a AWS Beanstalk Single Instance, getting refused to connect
I'm trying to get HTTPS working on a AWS Beanstalk Python/Django Single instance environment. I've worked through several issues but now I'm stuck, the build deploys and the site works on HTTP, but on HTTPS I get ERR_CONNECTION_REFUSED and nothing appears in the logs that I can see. Started with the directions here: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/https-singleinstance-python.html The first issue I ran into was a deployment error Unhandled exception during build: Yum does not have mod24_ssl available for installation and based on this post, I modified it to mod_ssl and that fixed it. The second issue I ran into was another deployment error Command 01killhttpd failed , so I removed those commands based on this post. This was successful in getting the environment to deploy and it works with HTTP, but with HTTPS I just get a refused connection and I can't figure out why. I've poured through the logs several times and see nothing. Here are the full logs. Any help is greatly appreciated. Here are the two files I have created under .ebextensions folder: https-instance.config packages: yum: mod_ssl : [] files: /etc/httpd/conf.d/ssl.conf: mode: "000644" owner: root group: root content: | LoadModule wsgi_module modules/mod_wsgi.so WSGIPythonHome /opt/python/run/baselinenv WSGISocketPrefix run/wsgi WSGIRestrictEmbedded On Listen 443 … -
Django doesn't set cookie
I have a problem setting cookies in Django. Basically I have 3 different cookie I wanna set: Session ID Access token Refresh token For some reason Access and Refresh tokens are set, but the Session ID (SSID) doesn't set. If I change key of "SSID" to for example "TEST_COOKIE" it passes and I can see it in dev tools. However I need SSID and for some magical reason it doesn't work. Here's example of my code: class AuthResponse(SuccessResponse): def __init__(self, data={}, ssid='', access_token: str = '', refresh_token: str = '', **kwargs): super().__init__(data, **kwargs) self.set_cookie(key=settings.SESSION_COOKIE_NAME, value=ssid,) if access_token: self.set_cookie(key=settings.ACCESS_KEY_COOKIE_NAME, value=access_token,) if refresh_token: self.set_cookie(key=settings.REFRESH_KEY_COOKIE_NAME, value=refresh_token,) AuthResponse inherits from SuccessResponse which is based on DjangoJsonResponse, and DjangoJsonResponse eventually inherits from HttpResponse. So the question is - what could cause of getting rid of "SSID" cookie? I tried to look around and find if all the data appears in init function and apprently eveyrthing is fine. All data, ssid, access_token and refresh_token come through, but only "SSID" doesn't get set. As well I tried to use "httponly" and "secure" while setting cookies, but it didn't help. There was an idea that might be middleware affects somehow on this, however I don't know who to … -
How to buffer exception objects with its traceback to be inspected later
I have a user submitted data validation interface for a scientific site in django, and I want the user to be able to submit files of scientific data that will aid them in resolving simple problems with their data before they're allowed to make a formal submission (to reduce workload on the curators who actually load the data into our database). The validation interface re-uses the loading code, which is good for code re-use. It has a "validate mode" that doesn't change the database. Everything is in an atomic transaction block and it gets rolled back in any case when it runs in validate mode. I'm in the middle of a refactor to alleviate a problem. The problem is that the user has to submit the files multiple times, each time, getting the next error. So I've been refining the code to be able to "buffer" the exceptions in an array and only really stop if any error makes further processing impossible. So far, it's working great. Since unexpected errors are expected in this interface (because the data is complex and lab users are continually finding new ways to screw up the data), I am catching and buffering any exception … -
ERR_CONNECTION_TIMED_OUT error is returned in the site after deploing a Django application to Heroku
I just re-deployed an application in the new Eco Dyno and provisioning a new PostgreSQL datbase, however after deploying successfully, when I try to open the application, this HTTP error is returned ERR_CONNECTION_TIMED_OUT and the application never opens. I also updated the stack from heroku-20 to heroku-22 and it is not working on both. Is there any additional configuration that I need to complete? This is the log from the latest deploy 2023-01-30T22:13:55.000000+00:00 app[api]: Build started by user farmacia@aselsi.org 2023-01-30T22:14:32.846408+00:00 app[api]: Deploy c6f350bc by user farmacia@aselsi.org 2023-01-30T22:14:32.846408+00:00 app[api]: Release v23 created by user farmacia@aselsi.org 2023-01-30T22:14:33.126404+00:00 heroku[web.1]: Restarting 2023-01-30T22:14:33.141734+00:00 heroku[web.1]: State changed from up to starting 2023-01-30T22:14:34.066230+00:00 heroku[web.1]: Stopping all processes with SIGTERM 2023-01-30T22:14:34.109732+00:00 app[web.1]: [2023-01-30 22:14:34 +0000] [4] [INFO] Handling signal: term 2023-01-30T22:14:34.109979+00:00 app[web.1]: [2023-01-30 22:14:34 +0000] [9] [INFO] Worker exiting (pid: 9) 2023-01-30T22:14:34.110205+00:00 app[web.1]: [2023-01-30 22:14:34 +0000] [10] [INFO] Worker exiting (pid: 10) 2023-01-30T22:14:34.310286+00:00 app[web.1]: [2023-01-30 22:14:34 +0000] [4] [INFO] Shutting down: Master 2023-01-30T22:14:34.461478+00:00 heroku[web.1]: Process exited with status 0 2023-01-30T22:14:35.372879+00:00 heroku[web.1]: Starting process with command `gunicorn aselsi.wsgi` 2023-01-30T22:14:36.441571+00:00 app[web.1]: [2023-01-30 22:14:36 +0000] [4] [INFO] Starting gunicorn 20.1.0 2023-01-30T22:14:36.441910+00:00 app[web.1]: [2023-01-30 22:14:36 +0000] [4] [INFO] Listening at: http://0.0.0.0:54892 (4) 2023-01-30T22:14:36.441956+00:00 app[web.1]: [2023-01-30 22:14:36 +0000] [4] [INFO] Using worker: sync … -
Django rest framework unsupported media type with image upload
this is my first time trying to upload image to django rest framework, i am using svelte for my front end and using the fetch api for requests. i am have an error that i cannot solve. all requests containing images return an unsupported media type error. Back End i have added these line to my settings.py # Actual directory user files go to MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'mediafiles') # URL used to access the media MEDIA_URL = '/media/' my simplified views.py @api_view(['GET', 'POST']) @permission_classes([IsAuthenticated]) @parser_classes([FormParser, MultiPartParser]) def products(request): if request.method == 'POST' and isPermitted(request.user, 'allow_edit_inventory'): serializer = ProductSerializer(data=request.data) serializer.initial_data['user'] = request.user.pk if serializer.is_valid(): serializer.save() return Response({'message': "product added"}, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) my urls.py from django.contrib import admin from django.urls import path, include from rest_framework.authtoken import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('api/', include("API.urls")) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and finally my models.py def product_images_upload_to(instance, filename): return 'images/{filename}'.format(filename=filename) class Product(models.Model): name = models.CharField(max_length=200) image_url = models.ImageField(upload_to=product_images_upload_to, blank=True, null=True) Front End my file upload component in svelte, the exported image variable is what get used in the request in the following code. export let avatar, fileinput, image; const onFileSelected = (e) => { image … -
Django Admin: search_fields with an optional null value
I have a Django Admin model as such. class ImportedItemAdmin(admin.ModelAdmin): autocomplete_fields = ["author"] search_fields = ("author__username",) The problem here is that the Author might be nil which causes a 'NoneType' object has no attribute 'username' error. Is there a way to support both nil authors and still search by username? -
File upload using Django framework
I need insights on how to upload a file on click of a save button.I have to upload a file and also capture user selections and save them(user selections) in a file when I click on "save". And then once the file uploaded successfully run button should get enabled and when I click on run button , uploaded file should get processed as per the user inputs. I have created a simple form and a view to upload a file on click of a submit button,but I dont know how to have a save button before submit. My View: def projects_upload(request): print(settings.MEDIA_ROOT) if request.method=='POST': upload_request=UploadFile() upload_request.file=request.FILES['file_upload'] upload_request.save() Form: <form action="uploadProject" method="post" enctype="multipart/form-data"> {% csrf_token%} <input type="file" name="file_upload" id="choose_upload_file" value="" accept=".zip,.rar,.7z,.gz,"></br> <input type="submit" class="btn btn-secondary btn-block" value="upload" id="file_upload1"> </form> -
Django - Postgres connection
I am super beginner, but want to learn super fast building web application. I am right now developing an Income-Expense web app on Django Framework (Python, js and Ajax). I am now stuck with the server and get different errors. Anyone can support me ? ERROR "django.db.utils.OperationalError: connection to server on socket "/tmp/.s.PGSQL.5432" failed: fe_sendauth: no password supplied" I think I shut down everything not properly and when a came back my virtual environment was not working. Thank You Don't know what to try more