Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Vue function to display formatted date
I have a django model which has two datetime fields which are created and updated which needs to be displayed on front end when object is created and display the updated date when object is updated how can i achieve this on vue i have added just created date but it needs to be formated and should display updated date when object is updated. <div class="table-wrapper"> <vue-table type="document" :headers="headers" :items="items" :processing="is_processing" :ordering="ordering" :pagination="pagination" @update:pagination="updatePagination($event)" @update:ordering="updateOrdering($event)" > <template slot="row" slot-scope="{ row, index }"> <td v-text="row.created"></td> </template> </vue-table> </div> {% endblock %} {% block footer_scripts %} {{ urlParams|json_script:"url-params-data" }} <script type="text/javascript"> </script> <script type="text/javascript"> var vm = new Vue({ components: { Multiselect: window.VueMultiselect.default, VueTable: window.VueTable }, mixins: [ window.paginatedDataMixin ], el: '#wrapper', delimiters: ["<%","%>"], data: { api_url: list_api_url, headers: [ { 'name': 'Date', 'field': 'created', 'width': '20%' }], filtering: { }, }, mounted: function() { this.loadData('search'); }, methods: { } }); </script> {% endblock %} v-text="row.created" shows created date in format 2022-11-02T23:56:47.698434 i need to show 02 Nov,2022 for the Date header and for the same date header v-text="row.updated" will show updated date if object is updated -
django_currentuser alternatives or how to get current user in Models.py
I have 2 Models in my django models.py. I need to get data from model2 to model1, but I don't need to store it anywhere in the model1 fields. I found @property of django and implemented that. My issue was that I need to get who the user is using request.user, which is not possible in models.py So how can I access user in django models? Is there any other packages? or is there any inbuilt django way which I haven't thought about? I searched and got a package called django-currentuser , unfortunately i'm using Django 4 which doesn't have a support. -
REACT + DJANGO - CORS Errors After Login - CORS header ‘Access-Control-Allow-Origin’ missing
We have a React + Django application on GCP App Engine instances and we are facing a CORS error when fetching data through our REST API. We have already installed and configured the CORS package for the Django Rest Framework in our django application: ` ALLOWED_HOSTS = [ 'xxxxxxxxxxxx.appspot.com', 'yyyyyyyyyyyy.appspot.com', ] CORS_ALLOWED_ORIGINS=[ 'http://localhost:3000', 'https://xxxxxxxxxxxx.appspot.com', 'https://yyyyyyyyyyyy.appspot.com', ] CORS_ALLOW_CREDENTIALS=True ` The preflight request is successful as well as the application login, which performs an async request to our backend: access-control-allow-origin: https://xxxxxxxxxxxxxxxxxxxxx.appspot.com access-control-allow-headers: accept, accept-encoding, authorization, content-type, dnt, origin, user-agent, x-csrftoken, x-requested-with access-control-allow-methods: DELETE, GET, OPTIONS, PATCH, POST, PUT access-control-max-age: 86400 The correct URL is passed through the allow-origins header. The actual GET request is then blocked with a 400 response code from the browser and the following error message: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://xxxxxx.appspot.com/api/entities?page_size=10. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 400. The strangest thing is that we are able to login into the application and that uses an async request to the same domain, only after we login does this error appear. We have gone through several stackoverflow pages and different configurations (Eg. Using Regex in he allow ORIGINS configuration) but nothing … -
Connect to Postgres on Heroku with Django properly
I'm new to Django and Heroku. I'm confused about how I should connect to Postgres database on Heroku from my Django app considering the fact that all the credentials and DATABASE_URL could be changed. Firstly, to connect to my Postgres on Heroku I started by using environment variables and hardcoded them in my Heroku dashboard. Then I figured out that it is a bad practice because the values can be changed. I checked this guide by Heroku where they recommend adding this to settings: DATABASES['default'] = dj_database_url.config(conn_max_age=600, ssl_require=True) With that, I added my DATABASE_URL to my .env file - because otherwise, the URL will be empty. Now I can get all the correct database credentials in my DATABASE that are the same as in my dashboard. So halfway there. Then I deleted all the hardcoded environment variables from my Heroku dashboard. Then when I tried to heroku run python src/manage.py migrate -a myapp data, I received an error: django.db.utils.OperationalError: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory Is the server running locally and accepting connections on that socket? As I understand it, the problem is that it can't connect to the database (maybe because I deleted … -
django-admin startproject myworld cannot work on mac
I am learning django but stuck at beginning of start project as below in terminal: kevinlin@kevindeMacBook-Pro ~ % django-admin startproject myworld kevinlin@kevindeMacBook-Pro ~ % I have installed python but version 2.7 shown on terminal, 3.10 version shown on python shell. I am wondering if the issue is caused by running version 2.7 on terminal ? kevinlin@kevindeMacBook-Pro ~ % python --version Python 2.7.18 Python 3.10.7 (v3.10.7:6cc6b13308, Sep 5 2022, 14:02:52) I have checked all of pip/django/virtlenv have been installed. I have tried to search solutions on google and here but cannot solve the issue. -
Combine today date and input type=time in DateTimeField in Django
Here I am using Django 3.0 and Python 3.7 Here I am getting time from django template and i need to combine this time and today date as save it in database as DateTimeField Here is my models.py class WorkTime(models.Model): client = models.ForeignKey(Client,on_delete=models.CASCADE) start_time = models.DateTimeField() end_time = models.DateTimeField() total_time = models.TimeField(blank=True, null=True) Here is my views.py class AddWorkTimeView(View): def get(self, request): client = request.user.client return render(request,'core/work_time_form.django.html') def post(self, request): c = request.user.client start_time = request.POST.get('start_time') # print start_time - 11:15 end_time = request.POST.get('end_time') # print end_time - 14:15 WorkTime.objects.create(client=c,start_time=start_time,end_time=end_time) return redirect('work_times') Here is my work_time_form.django.html <form class="form-horizontal" method="post"> {% csrf_token %} <div class="row"> <div class="span10 offset1"> <div class="control-group"> <label class="control-label pull-left">Start Time</label> <input type="time" step="900" class="input_box" name="start_time"> </div> <div class="control-group"> <label class="control-label pull-left">End Time</label> <input type="time" step="900" class="input_box" name="end_time"> </div> <div id="form-buttons-container" class="form-actions"> <div class="controls"> <input type="submit" class="btn btn-inverse" value="Save"> </div> </div> </div> </div> </form> Here what format i want it to save to my datebase Example: 2020-11-03 10:30:00 (here date is today date) And also calculate the time difference between start_time and end_time in minutes and save it to total_time field To achieve this what changes i need to do to my code Please help me to solve … -
How to make the data of table kept even after containers deleted?
My purpose is to keep data even after deleting and rebuilding containers. More specifically, I want to keep data even after putting like "docker-comand down" or "docker-comand up -d --build". My environment is Docker Django PostgreSQL Nginx Gunicorn docker-compose.prod.yml version: '3.8' services: web: build: context: ./app dockerfile: Dockerfile.prod command: gunicorn ecap.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles expose: - 8000 env_file: - ./.env.prod depends_on: - db db: image: postgres:13.0-alpine volumes: - db_data:/var/lib/postgresql/data/ env_file: - ./.env.prod.db nginx: build: ./nginx volumes: - ./static_volume:/home/app/web/staticfiles - ./media_volume:/home/app/web/mediafiles ports: - 80 depends_on: - web volumes: db_data: static_volume: media_volume: I assume that the problems is how to write volumes in the yml file. Although I followed the shown way, I cannot keep the data. -
How to load ml model joblib dump file into celery task?
from transformers import pipeline import joblib cls = pipeline("automatic-speech-recognition", "facebook/wav2vec2-base-960h") joblib.dump(cls, "model/wav2vec2-base-960h-model-joblib") I used "facebook/wav2vec2-base-960h" to recognize/transcribe text from audio. en_wav2vec2_model = joblib.load(os.path.dirname(os.path.abspath(file))+"/model/wav2vec2-base-960h-model-joblib") using this way I load that model. Now, This model loads properly when it is in a synchronized process. But when I use this model in the celery task it is hang. there is no error showing that the task is created but can not complete. -
csrf_exempt not working in url Django Project
I keep receiving Forbidden (CSRF cookie not set.): /registration/ I have found many answers but non of them are matching with my project. Here is the Django Rest Framework urls with my attempt to exempt CSRF: path('dj-rest-auth/', csrf_exempt(include('dj_rest_auth.urls'))), path('dj-rest-auth/registration/', csrf_exempt(include('dj_rest_auth.registration.urls'))), I dont have anything in the views since the Registration and Login are already built in 'dj_rest_auth.registration.urls' The registration process is working fine from the web page but when I trying to create using flutter it is not allowing me. My question: How can I fix this problem without creating a login in or registration in the views page? -
Getting count of one column that has a distinct on two columns
Here is a simplified representation of my models: class Post(models.Model): user = models.ForeignKey(User) template_id = models.IntegerField(null=True) ... What I want to do is show the number of times a template has been used by users. So when I list out the templates, I want to be able to say Used by X users. The main draw is that I don't only want to count a user once (so if a user uses a template twice, they still count as "one use case"). All stackoverflow posts talk about doing something like this: counts = Post.objects.all().values("template_id").order_by().annotate(count=Count("template_id")) But that obviously double counts a user that uses the same template twice. I was able to do a distinct on template_id and user pairings like so: # Printing this out, I get 2 distinct entries in the QuerySet Post.objects.all().values("template_id", "user").distinct() However, when I try to get the counts of template_id (the code below), it seems to ignore the distinct and still double counts users. # Printing this out I get `count` = 3, which double counts a user. Post.objects.all().values("template_id", "user").distinct().values("template_id").annotate(count=Count("template_id")) Am I missing something here? -
multiple USERNAME_FIELD in djangorestframework?
How can i allow users to authenticate via multiple username field e.g(email | phone_number as USERNAME_FIELD)?? I have a custom User model---> in which I have a USERNAME_FIELD set to 'email'. settings.py AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', #THis is a default Backend which points to CustomUser's USERNAME_FIELD. 'account.backends.AuthenticateBackend', ##Custom Backend which tells to use phone number as USERNAME_FIELD. ] Here's the issue! It works fine if I use default obtain_auth_token view e.g.(allows me to login via multiple field)---> but whenever I write my own login logic it skips default model backend settings thus, it greets me with error. ValueError: Field 'phone_number' expected a number but got 'someEmail@gmail.com'. -
how to fix vscode terminal delay in win7
every command something it take so long time 30s to 1min waiting answering... -
Blocking IOError when using django + uwsgi
I am getting an error when there are too many requests coming to my application. Previously we did not notice so much issues, but recently we have seen that we get the error: BlockingIOError: [Errno 11] write could not complete without blocking print(ServDHCPRelay,"ServDHCPRelay") File "/apps/netadc3/.venvs3/netadc3.8/lib64/python3.8/site-packages/colorama/ansitowin32.py", line 41, in write self.__convertor.write(text) File "/apps/netadc3/.venvs3/netadc3.8/lib64/python3.8/site-packages/colorama/ansitowin32.py", line 162, in write self.write_and_convert(text) File "/apps/netadc3/.venvs3/netadc3.8/lib64/python3.8/site-packages/colorama/ansitowin32.py", line 190, in write_and_convert self.write_plain_text(text, cursor, len(text)) File "/apps/netadc3/.venvs3/netadc3.8/lib64/python3.8/site-packages/colorama/ansitowin32.py", line 195, in write_plain_text self.wrapped.write(text[start:end]) File "/apps/netadc3/.venvs3/netadc3.8/lib64/python3.8/site-packages/colorama/ansitowin32.py", line 41, in write self.__convertor.write(text) File "/apps/netadc3/.venvs3/netadc3.8/lib64/python3.8/site-packages/colorama/ansitowin32.py", line 162, in write self.write_and_convert(text) File "/apps/netadc3/.venvs3/netadc3.8/lib64/python3.8/site-packages/colorama/ansitowin32.py", line 190, in write_and_convert self.write_plain_text(text, cursor, len(text)) File "/apps/netadc3/.venvs3/netadc3.8/lib64/python3.8/site-packages/colorama/ansitowin32.py", line 196, in write_plain_text self.wrapped.flush() BlockingIOError: [Errno 11] write could not complete without blocking The error happens on print statements. We upgraded from python3.6 -> rh-python3.8 recently and we are using django 3.2! uWSGI version 2.0.20 -
Generate report date not included
I am trying to generate report in pdf in Django but the date of the report is not showing up. How can you include the date of report the fromdate and todate in the header of the PDF once the dates is saved in the model? Is there something I missed? Please see below the codes. Thanks View.py def GenerateInvoiceAccident(request): try: if request.method == 'POST': fromdate = request.POST.get('fromdate') todate = request.POST.get('todate') report = GenerateReport(user=request.user, fromdate=fromdate, todate=todate, report="Accident Causation PDF") report.save() print(fromdate, todate) # incident_general_accident = IncidentGeneral.objects.filter(user_report__status = 2).values('accident_factor__category').annotate(Count('severity'), filter=Q(severity='Damage to Property')) incident_general_accident = IncidentGeneral.objects.filter(status = 2, date__range=[fromdate, todate ]) incident_general_accident1 = IncidentGeneral.objects.filter(status = 2,severity='Fatal', date__range=[fromdate, todate ] ).annotate(Count('severity')) incident_general_accident2 = IncidentGeneral.objects.filter(status = 2,severity='Damage to Property', date__range=[fromdate, todate ] ).annotate(Count('severity')) incident_general_accident3 = IncidentGeneral.objects.filter(status = 2,severity='Non-Fatal', date__range=[fromdate, todate ] ).annotate(Count('severity')) incident_general_classification = IncidentGeneral.objects.filter(status = 2, severity="Damage to Property", date__range=[fromdate, todate ]).distinct('accident_factor') incident_general_collision = IncidentGeneral.objects.filter(status = 2, severity="Damage to Property", date__range=[fromdate, todate ]).distinct('accident_factor') #you can filter using order_id as well report1 = GenerateReport.objects.all().order_by('-created_at')[:1] except: return HttpResponse("505 Not Found") data = { 'incident_general_accident': incident_general_accident, 'incident_general_classification': incident_general_classification, 'incident_general_collision': incident_general_collision, 'incident_general_accident1': incident_general_accident1, 'incident_general_accident2': incident_general_accident2, 'incident_general_accident3': incident_general_accident3, 'report1':report1 # 'amount': order_db.total_amount, } pdf = render_to_pdf('pages/generate_report_pdf_accident.html', data) #return HttpResponse(pdf, content_type='application/pdf') # force download if pdf: response = HttpResponse(pdf, … -
Local database works but on Heroku I get: operator does not exist: text % unknown
I've been dealing with this issue for days. I have a Postgres (version 13) database set up locally and on Heroku. Django and Python version are identical. When I make an api call to my local database, everything is fine - but when I make the call to the Heroku database I get the error below. The search input (eg 'party') is a string, "trademark_trademark" model is type models.TextField(null=True) I understand that the error is suggesting that I need ensure that the query input is of the right type. Can string not query a TextField. If so what type does it need to be. I'm an amateur and can't wrap my head around it - any idea what the problem might be? ProgrammingError at /trademarks/api/trademarks/ operator does not exist: text % unknown LINE 1: ...rademark" WHERE "trademark_trademark"."trademark" % 'party' ... ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. Request Method: GET Request URL: https://CENSORED.herokuapp.com/trademarks/api/trademarks/?q=party&class_nos=0&no_related=true Django Version: 4.0.5 Exception Type: ProgrammingError Exception Value: operator does not exist: text % unknown LINE 1: ...rademark" WHERE "trademark_trademark"."trademark" % 'party' ... ^ HINT: No operator matches the given name and argument types. You … -
Django: referencing a namespace in a template during a unit test gives "not a registered namespace" error
I am just learning how to unit test so I'm sure I'm not understanding some core principal. I have custom 400 and 500 error handlers that return a template indicating the error to the user. Now, in practice, when I run my site, these work perfectly! Errors get caught and the templates get generated exactly as anticipated. The difficulty comes when I try to write unit tests for the 500 error. What occurs: any references to a namespace (in this case, 'base') throws an error. Traceback (most recent call last): File "/home/--------/Documents/projects/--------/venv/lib/python3.10/site-packages/django/urls/base.py", line 71, in reverse extra, resolver = resolver.namespace_dict[ns] KeyError: 'base' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/--------/Documents/projects/--------/base/testing/test_views.py", line 50, in test_handler_renders_template_response response = self.client.get('/500/') File "/home/--------/Documents/projects/--------/venv/lib/python3.10/site-packages/django/test/client.py", line 836, in get response = super().get(path, data=data, secure=secure, **extra) File "/home/--------/Documents/projects/--------/venv/lib/python3.10/site-packages/django/test/client.py", line 424, in get return self.generic( File "/home/--------/Documents/projects/--------/venv/lib/python3.10/site-packages/django/test/client.py", line 541, in generic return self.request(**r) File "/home/--------/Documents/projects/--------/venv/lib/python3.10/site-packages/django/test/client.py", line 805, in request response = self.handler(environ) File "/home/--------/Documents/projects/--------/venv/lib/python3.10/site-packages/django/test/client.py", line 153, in __call__ response = self.get_response(request) File "/home/--------/Documents/projects/--------/venv/lib/python3.10/site-packages/sentry_sdk/integrations/django/__init__.py", line 409, in sentry_patched_get_response rv = old_get_response(self, request) File "/home/--------/Documents/projects/--------/venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 140, in get_response response = self._middleware_chain(request) File "/home/--------/Documents/projects/--------/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 57, in inner response = response_for_exception(request, exc) … -
How to multiply to columns in different table and get another coloum as output in django orm
I have three tables First one is product table consist of product details and price Second one is customer table with customer details And a cart table with customer_id and product _id as foreign key and qty field for quantity of product I want join cart table and product table and get an additional field called total price that is the result of price in product *qty in cart How to do this in django orm I tried f function but it didn't work -
Infinite POST request on uploading file with Django
I try to upload some files to a server through a web interface with Django. HTML : <form method="post" enctype="multipart/form-data" name="upload_file"> {% csrf_token %} <input type="file" name="uploaded_file_list" multiple> <button class="rounded-full bg-violet-200 text-violet-700 block p-2" name="upload_file" value="dummy" type="submit">Ajouter des fichiers</button> </form> views.py def media_manager(request): file_manager = MediaManager.server.FileManager(django.conf.settings.USER_FILE_ROOT) # POST utilisé pour associer les tags aux images if request.method == "POST": print(request.POST) if request.POST.get("upload_file"): for uploaded_file in request.FILES.getlist("uploaded_file_list"): file_manager.add_file(uploaded_file) context_dict = {} context_dict["filtered_file_list"] = MediaManager.filters.ImageFilter(request.GET, queryset=MediaManager.models.UserImage.objects.all()) return django.shortcuts.render(request, "MediaManager/media_manager.html", context=context_dict) FileManager.py def add_file(self, uploaded_file): file_system_storage = django.core.files.storage.FileSystemStorage(location=self._user_dir_absolute_path) file_system_storage.save(uploaded_file.name, uploaded_file) FileManager also updates context_dict["filtered_dile_list"] with the files uploaded. When I upload a file on the browser, the file is correctly uploaded and the web display also correctly add it on the page. I can see the upload POST request. But this operation is repeated infinitely. Here is the log (with a request.POST print) : <QueryDict: {'csrfmiddlewaretoken': ['vCHAoeGg3QVIZDuHAls8lmV7Y8MXHqxGeWQj16N2zJcCUfoML4pVcnsmJGk7R5Er'], 'upload_file': ['dummy']}> [02/Nov/2022 22:03:23] "POST /media_manager/ HTTP/1.1" 200 19214 1 static file copied to '/home/gautitho/workspace/MonPetitNuage/MonPetitNuage/static', 185 unmodified. <QueryDict: {'csrfmiddlewaretoken': ['vCHAoeGg3QVIZDuHAls8lmV7Y8MXHqxGeWQj16N2zJcCUfoML4pVcnsmJGk7R5Er'], 'upload_file': ['dummy']}> [02/Nov/2022 22:03:24] "POST /media_manager/ HTTP/1.1" 200 19580 [02/Nov/2022 22:03:24] "GET /static/MediaManager/user/Couleurs-logo-Overwatch.jpg HTTP/1.1" 200 63919 1 static file copied to '/home/gautitho/workspace/MonPetitNuage/MonPetitNuage/static', 186 unmodified. <QueryDict: {'csrfmiddlewaretoken': ['vCHAoeGg3QVIZDuHAls8lmV7Y8MXHqxGeWQj16N2zJcCUfoML4pVcnsmJGk7R5Er'], 'upload_file': ['dummy']}> [02/Nov/2022 22:03:25] "POST /media_manager/ HTTP/1.1" 200 19959 … -
How do I get and pass context from one form to another based on primary/foreign key fields?
I am currently building a website that will allow the sale of mixing and mastering services. As it is a small set of services, I don't need a shopping cart or any elaborate form of ordering. Instead, I would like a customer details page (which informs my 'Customer' model), an order page where the customer selects what exactly they will be purchasing and uploads any relelvent files (which also informs my 'Order' model), and finally sends the customer to a stripe checkout page. Currently, the Custome rdetails form is up and running and saving the data to the appropriate database model. Once they click continue, I am struggling to understand how to store the primary key of the Customer instance the user created upon filling out the form, and saving this data in the next form through the foreign key relationship. Similarly, before being sent to Stripe checkout, I would like to create an 'Order Review' page, reviewing the details of their order. I'm not sure how to pull the primary key of the Order intance that was just created in order to for a Model view on the subsequent page. I believe what I;m missing in order to achieve … -
How do I render a PDF in Django using FileResponse
I have a simple function to Open a PDF file, I want to render it within my Django as part of a POST function. def view_pdf(request, pdfpath): filename = pdfpath.replace('\\', '/') name = filename.split('/')[-1] if os.path.exists(filename): response = FileResponse(open(filename, 'rb'), content_type='application/pdf') response['Content-Disposition'] = f'inline; filename={name}' # user will be prompted display the PDF in the browser # response['Content-Disposition'] = f'filename={name}' # user will be prompted display the PDF in the browser return response else: return HttpResponseNotFound('Cannot find the PDF') My view calls this with return view_pdf(request, pdfpath) How do I actually get this to open as a new Tab ? The HTML has a submit button that calls some ajax functions <button type="submit" onclick="window.submitPAGE()" class="btn waves-effect waves-light btn-primary"><i class="fa fa-print"></i></button> So I cant turn it into a FORM because I cant pass the data form the function <form method="POST" target="_blank"> <button type="submit" class="btn waves-effect waves-light btn-primary"><i class="fa fa-print"></i></button> -
Update data in table which has foreign keys in Django
I have two tables where one is connected to the other with a foreign key. The model store_table already consists of three rows, for three different stores. I am now trying to update the model price_table but I am not quite sure that I understand how to utilize the foreign keys, so that it knows which price_table item to be connect to which store_table id. Any suggestions out there on how to achieve this? My two models class store_table(models.Model): store = models.CharField(max_length=100, null=True) number = models.BigIntegerField(null=True) class Meta: unique_together = ( ( "store", "number", ), ) class price_table(models.Model): price = models.CharField(max_length=100, null=True) dates = models.DateField(null=True, blank=True) store_id = models.ForeignKey( store_table, on_delete=models.CASCADE, default=None ) class Meta: unique_together = ( ( "dates", "price", ), ) My code update_models = price_table( dates=dates, price=price ) update_models.save() -
How i can get JSON list without attributes ("count": 3, "next": null, "previous": null, "results":)
I have JSON like this: {"count":3,"next":null,"previous":null,"results":[{"name":"Max","slug":"DrMax","directions":["Surgery","Stomach"],"description":"Surgery","work_experience":"2","birt_date":"2018-12-04"},{"name":"Ban","slug":"0","directions":["X-Ray"],"description":"Xray","work_experience":"6","birt_date":"2022-11-02"},{"name":"qwe","slug":"qwe","directions":["Surgery","X-Ray","Stomach"],"description":"Xray","work_experience":"6","birt_date":"2022-11-14"}]} And I want to get JSON like this [{"name":"Max","slug":"DrMax","directions":["Surgery","Stomach"],"description":"Surgery","work_experience":"2","birt_date":"2018-12-04"},{"name":"Ban","slug":"0","directions":["X-Ray"],"description":"Xray","work_experience":"6","birt_date":"2022-11-02"},{"name":"qwe","slug":"qwe","directions":["Surgery","X-Ray","Stomach"],"description":"Xray","work_experience":"6","birt_date":"2022-11-14"}] -
View is returning an HttpResponse, but says it returns None
I have a button in one of my views that triggers a function "compileUpdate" and then returns a file as a response. This was working previously but now I receive the error: "ValueError: The view didn't return an HttpResponse object. It returned None instead." The block of code below essentially: Gets the correct campaign Formats the path of the files to compile Checks if a specific directory exists, and if not creates it Calls the compileUpdate function Returns the file as a http response Non-working file creation and response if req == "Bulk Update": cmp_id = request.headers.get('cmp') campaign = Campaign.objects.get(id=cmp_id) parent_dir = os.path.normpath(os.getcwd() + os.sep + os.pardir) submittedFolder = os.path.join(parent_dir, "SubmittedReviews", "", str(cmp_id) + "-" + campaign.system.name, "") cmp_files = glob.glob(os.path.join(submittedFolder,'*')) archive = os.path.join(parent_dir, "Archive", "", str(campaign.id) + "-" + campaign.system.name, "") if os.path.exists(archive) == False: os.mkdir(archive) bulk_update = os.path.join(archive, str(campaign.id) + "-" + campaign.system.name + "_bulk_update.csv") print(bulk_update) with open(bulk_update, 'w') as bulk_out: writer = csv.writer(bulk_out) compileUpdate(cmp_files, campaign, writer) bulk_out.close() time.sleep(2) file = str(bulk_update).split("/")[-1] with open(bulk_update, 'rb') as fh: response = HttpResponse(fh.read()) response['Content-Type'] = 'application/vnd.ms-excel' response['Content-Disposition'] = 'inline; filename="{}"'.format(os.path.basename(bulk_update)) response['X-Accel-Redirect'] = f'/archive/{file}' return response As mentioned above, this errors out saying that I am returning None rather than an http … -
How to submit an update form and create form at the same time in Django?
I am trying to update a model "Stock", then create a new "StockTransaction" at the same time. I want to accomplish this using two different forms submitted together. I am able to get the stock update transaction to work, but when I try to is_valid() on the transaction form, it always returns false. I can't figure out why it is returning false. here are all of the relevant code sections that are used. Any help is appreciated. Thank you in advance! def buyStock(request, pk): stock = Stock.objects.get(id=pk) form = StockForm(instance=stock) tform = StockTransForm() if request.method == 'POST': form = StockForm(request.POST, instance=stock) form.instance.buyPrice = stock.ticker.price form.instance.dateOfPurchase = date.today() form.instance.forSale = False tform.instance.stockID = stock.stockID tform.instance.buyPrice = stock.buyPrice tform.instance.sellPrice = stock.ticker.price tform.instance.broker = form.instance.broker tform.instance.buyer = form.instance.ownerID tform.instance.seller = stock.ownerID tform.instance.ticker = stock.ticker if form.is_valid() and tform.is_valid(): form.save() tform.save() class StockTransaction(models.Model): transactionID = models.AutoField(primary_key=True) ticker = models.ForeignKey(PublicCompany, on_delete=models.CASCADE, default=None, related_name='stocktrans-ticker+') stockID = models.IntegerField() buyer = models.ForeignKey(FinancialAccount, on_delete=models.PROTECT, default=None, related_name='stocktrans-buyer+') seller = models.ForeignKey(FinancialAccount, on_delete=models.PROTECT, default=None, related_name='stocktrans-seller+') sellPrice = models.DecimalField(max_digits=7, decimal_places=2) buyPrice = models.DecimalField(max_digits=7, decimal_places=2) date = models.DateField(auto_now_add=True) broker = models.ForeignKey(Agent, on_delete=models.PROTECT, default=None, related_name='stocktrans-broker+') class Stock(models.Model): ownerID = models.ForeignKey(FinancialAccount, on_delete=models.CASCADE, default=None, related_name='stock-owner+')#on delete maybe change buyPrice = models.DecimalField(max_digits=7, decimal_places=2) broker = models.ForeignKey(Agent, on_delete=models.PROTECT, default=None, … -
Django Model: how to find list of auto-generated fields
Is there any Django built-in function that return a list of all auto-generated fields from a Django model? Something like: MyModel._meta._get_auto_generated_fields()