Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use JavaScript in included components in Django?
In short, how to use JavaScript in the component that will be then included in the main page? A standard approach in Django templates is to create a base.html template and then extend it. That base template usually has blocks like content, extra_js, and extra_css. The extended template looks like {% extend 'base.html' %} {% block content %} <div> some content </div> {% endblock %} {% block extra_js %} # some js code here {% endblock %} I need to create a component that will be included on several pages and I need to use JavaScript inside that component. I know that it will be included only on pages that extend base.html, the page that includes it will look like {% extend 'base.html' %} {% block content %} <div> {% include 'component.html' %} </div> {% endblock %} {% block extra_js %} # some js code here {% endblock %} However, component.html knows nothing about extra_js block because it doesn't extend base.html, I cannot use that block in component.html, and if I just put some JavaScript code in it then after the template is rendered any JavaScript in component.html will end up being in the middle of the body of the … -
django-filer import file paths from mysql to postgresql
Recently I changed the database in my Django app from MySQL to PostgreSQL. I moved all text values and folders successfully from staging to the production environment but I am struggling with paths to media files that are stored on Azure Storage. I am using the same settings in my settings both in production and staging environments: DEFAULT_FILE_STORAGE = 'backend.custom_azure.AzureMediaStorage' MEDIA_LOCATION = "media" AZURE_ACCOUNT_NAME = config('AZURE_ACCOUNT_NAME') AZURE_CUSTOM_DOMAIN = f'{AZURE_ACCOUNT_NAME}.blob.core.windows.net' MEDIA_URL = f'https://{AZURE_CUSTOM_DOMAIN}/{MEDIA_LOCATION}/' The problem is that I connected all files on staging and when I am trying to manually export from mysql and import in postgresql filer_file and filer_image tables I am getting this error: Exception Type: Polymorphic Type Invalid at /homepage Exception Value: Content Type 37 Question Basically what I want is to copy folders and files that are on staging (paths stored in MySQL) and pasting/uploading/importing them on production (paths stored in PostgreSQL) so my question is how to resolve this issue. I don't want to connect each image once again in each model because there are hundreds of them already. Is there any way I can import them into PostgreSQL in a way that when I open the admin panel in the production environment it will show … -
Why is the returned result of the Elasticsearch response still caped at 10000 when the parameter max_result_window has been changed?
I have a Django application with Elasticsearch. I have an index where I need to render more than 10 000 results. I changed manually the parameter max_result_window to render more than the 10 000 initial limit. But after changing the parameter max_result_window and the size in the body_search of my request, the result keeps being limited to 10 000. First, I have changed the parameter max_result_window to 12345 of the search_index, by using the method from the page Result window is too large, from + size must be less than or equal to: [10000] but was [100000]. I checked on http://localhost:9200/search_index/_settings, and I have the following result "max_result_window":"12345". Then I changed the parameter size of my body_search = {'query': {...}, 'size': 12345}. But the final result is always limited at 10 000. Does anyone has an idea what the change is not take into account in my search ? -
How to upload files through BSModalCreateView using an inline formset?
I'm currently trying to upload a file in a BSModalCreateView while using an inline formset and have it saved in a folder for testing purposes that has full permissions for read/write. When trying to print out which file was uploaded to the InMemoryUploadedFile class, nothing will be prinited out. If I comment out the function def get_success_url() (views.py) to throw an error, I can see the file is being uploaded to the InMemoryUploadedFile class: I'm not sure if I'm missing something in the function def doc_valid() (views.py) or something with my inline formset. Any guidance will be appreciated, thanks! base.py MEDIA_ROOT = os.path.join('home/my-location/') MEDIA_URL = 'media/' Views.py from datetime import datetime as dt from django.urls import reverse from bootstrap_modal_forms.generic import ( BSModalCreateView ) from users.forms.documents import DocumentForm, DocumentFormSet from users.models.documents import Document from users.models.users import User class DocumentCreateView(BSModalCreateView): form_class = DocumentForm template_name = 'partials/test.html' success_message = 'Document added successfully' def get_success_url(self): return reverse('users:detail', args=[self.kwargs.get(self.slug_url_kwarg)]) def get_context_data(self, *args, **kwargs): context = super(DocumentCreateView, self,).get_context_data(*args, **kwargs) context['action'] = 'Upload' context['object_type'] = 'a Document' context['user_to_edit'] = User.objects.get(username=self.kwargs.get(self.slug_url_kwarg)) if self.request.POST: context['docfiles'] = DocumentFormSet(self.request.POST, self.request.FILES, instance=self.object) else: context['docfiles'] = DocumentFormSet(instance=self.object, initial={'user': context['user_to_edit'].id}) return context def doc_valid(self, request): context = self.get_context_data() form = context['docfiles'] self.object = form.save() … -
Invalid hex encoding in query string
im currently working on a DJango search with multiple query_params, since im using Sentry i found out that sometimes there's an issue triggered when you search for example something with percentages: "100% natural" "100% unique" "50% blah blah blah" Sentry: Unhandled Invalid hex encoding in query string. This is marked in the oauth lib if INVALID_HEX_PATTERN.search(query): raise ValueError('Invalid hex encoding in query string.') The current search code allows to pass any query_param like this: re_path(r"^search/?$", search_system, name="search") And inside the view i do have this: query = request.query_params.get("query") query = query.replace("%20", " ") if query else None i tried to replace the %20 for an space, but sometimes it happens and sometimes it doesn't so it happens randomly, i don't know if im doing something wrong, or actually the question would be: is there anything i could do to avoid triggering this alert without doing anything in sentry? for example like cleaning up the data like a form Thanks in advance. To avoid this issue i tried to set the query replace("%20", " "), my best guess is that the error is triggered when you have the "percentage + space" next to each other so the url looks like search/100%25%20natural … -
error while installing dj-rest-auth inside google cloud vm and i created a virtualenv
I am inside SSH window of VM I created a virtal environment using command :virtualenv -p python3.8 venv now i try to install dj-rest-auth using command pip install dj-rest-auth and i am receiving error Building wheels for collected packages: dj-rest-auth Building wheel for dj-rest-auth (setup.py) ... error But it allow me to install using sudo pip install dj-rest-auth but while running my django project it is not recognising and i am receiving module not found error Python 3.8.3 is the version can any one tell me the solution for it? -
Django - loop through the records and update database on conditions with scheduled task
How to run a scheduled task from example task file scheduled_task.py file to access models.py (e.g. Event) and if certain criteria is met, update one of the fields in database (example: event_status)? models.py class Events(models.Model): event_title = models.CharField(max_length=300) event_info = models.TextField(max_length=2000) event_date = models.DateField(default=now) event_time = models.TimeField(default='00:00') event_location = models.CharField(max_length=150) event_status = models.CharField(max_length=30, choices=EVENT_STATUS_CHOICES, default='New Event') def save(self, *args, **kwargs): if date.today() > self.event_date: self.event_status = 'Completed Event' super(Events, self).save(*args, **kwargs) What should be code to iterate through all events from database, and update it's record? scheduled_task.py from models import Events def verify_events(): all_events = Events.objects.all() for event in all_events: if event.event_date < date.today(): event.event_status = 'Completed Event' event.save() The code runs, but nothing happens (no error), db is not refreshed with changes. The current save() for Events under models.py does the work when you refresh the page, they it runs the save() function, but I want this to be always up to date without refreshing the page manually to trigger the save() function - so it can happen overnight (I am using Tasks in PythonAnywhere). Is the event.save() incorrect? not saving while integrating through the Events? Thanks for help -
Django - Apply model on many (1000's) foreign key objects in admin
I have a model of a football coach and a model of a membership payment which has a foreign key to the coach model. In the admin, I want to be able to apply the membership to a lot of coaches at once and not only to one coach. In essence, I imagine a raw_id field which is selectable. The coach has a field balance and the membership model deducts on save some amount from that field of the coach. Is something like this possible? Here are my models: class Trener(models.Model): class Meta: verbose_name = 'Trener' verbose_name_plural = 'Treneri' prezime = models.CharField(max_length=100) #new ime = models.CharField(max_length=100) balans = models.IntegerField() #new def __str__(self): return str(self.prezime) and my membership model: class Clanarina(models.Model): class Meta: verbose_name = 'Clanarina' verbose_name_plural = 'Clanarine' trener = models.ForeignKey(Trener, on_delete=models.CASCADE) datum_naplate = models.DateField() opis = models.CharField(max_length = 200, blank=True, null=True) iznos = models.IntegerField( verbose_name="iznos (uneti pozitivan broj)") # @property # def naplata(self): # self.trener.balans -= self.iznos # self.trener.save() # return def save(self, *args, **kwargs): self.trener.balans -= self.iznos self.trener.save() super(Clanarina, self).save(*args, **kwargs) Thank you very much in advance! I am new to django and am not really sure if I created my models in the right way! Any help … -
Paginated REST API endpoint for django-simple-history records, using Django REST Framework
I'm using django-simple-history to track model changes. It's easy enough to get all history records for a model class or a model instance: poll = Poll.objects.create(question="what's up?", pub_date=datetime.now()) poll.history.all() # and Choice.history.all() But what I'm looking to do is to have endpoints like /history/model and /history/model/1 that returns paginated history records for either the class or class instance. Now I've already got Django REST Framework (DRF) set up with pagination, and have all my views paginated, something like: class MyModelViewSet(viewsets.ModelViewSet): serializer_class = MyModelSerializer permission_classes = [permissions.IsAuthenticated] queryset = MyModel.objects.all() class MyModelSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = MyModel fields = ["name"] class MyModel(models.Model): name = models.CharField(max_length=100, unique=True) That all works fine. How can I paginate the django-simple-history records? Can I create a simple history serializer? Because there's not exactly a simple history model I can use (I think). -
Почему при запуске миграций не все поля модели создаются? [closed]
Вот модель class Kykyruza(models.Model): id = models.IntegerField(), docsname = models.CharField(max_length = 1000), chapternum = models.IntegerField(), chaptername = models.TextField(max_length = 1000), link = models.URLField() def __str__(self): return f"{self.id};" \ f" {self.docsname};" \ f" {self.chapternum};" \ f" {self.chaptername};" \ f" {self.link}" вот файл миграций и почему то в нём только два поля class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Kykyruza', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('link', models.URLField()), ], ), ] Удалял, создавал новое приложение, ничего не помогло, уже и не знаю что делать -
Django project doesnt insert into Oracle table
I'm building a integration app that consumes data from a API and save the sensitive information into a table inside a oracle database. My models succesfully migrated and created the tables and I was able to also succesfully consume and filter the data I need from the API, so I proceeded to use objects.update_or_create to populate my table with the data, initially it worked fine and inserted the information normally until it got stuck and stoped the querys. After that I droped the tables and started the migration process anew, and also changed my method to objects.create with .save(force_insert=True) to brute force the process and insert the data inside the table, but the problem persisted and I'm kinda lost not knowing what is wrong mainly because it doesnt raise any error nor exception and just remains stuck into the block. for item in value_list['itens']: print(item) i = Item.objects.using('adm_int').create( nature=item['nature'], nr_doc=item['nr_doc'], name=item['name'], value=item['value'], type_op=item['type'], description=item['history']['description'], ) i.save(force_insert=True) Inside the response from the API there'll be N number of itens, so I need to insert the data from each item into the table. When it begins the loop it doesnt insert the data and stops there. -
InvalidClientTokenId error when trying to access SQS from Celery
When I try to connect to SQS using Celery, I'm not able to. The worker crashes with the following message: [2022-10-28 14:05:39,237: CRITICAL/MainProcess] Unrecoverable error: ClientError('An error occurred (InvalidClientTokenId) when calling the GetQueueAttributes operation: The security token included in the request is invalid.') Traceback (most recent call last): File "/home/aditya/.local/lib/python3.10/site-packages/celery/worker/worker.py", line 203, in start self.blueprint.start(self) File "/home/aditya/.local/lib/python3.10/site-packages/celery/bootsteps.py", line 116, in start step.start(parent) File "/home/aditya/.local/lib/python3.10/site-packages/celery/bootsteps.py", line 365, in start return self.obj.start() File "/home/aditya/.local/lib/python3.10/site-packages/celery/worker/consumer/consumer.py", line 332, in start blueprint.start(self) File "/home/aditya/.local/lib/python3.10/site-packages/celery/bootsteps.py", line 116, in start step.start(parent) File "/home/aditya/.local/lib/python3.10/site-packages/celery/worker/consumer/tasks.py", line 38, in start c.task_consumer = c.app.amqp.TaskConsumer( File "/home/aditya/.local/lib/python3.10/site-packages/celery/app/amqp.py", line 274, in TaskConsumer return self.Consumer( File "/home/aditya/.local/lib/python3.10/site-packages/kombu/messaging.py", line 387, in __init__ self.revive(self.channel) File "/home/aditya/.local/lib/python3.10/site-packages/kombu/messaging.py", line 409, in revive self.declare() File "/home/aditya/.local/lib/python3.10/site-packages/kombu/messaging.py", line 422, in declare queue.declare() File "/home/aditya/.local/lib/python3.10/site-packages/kombu/entity.py", line 606, in declare self._create_queue(nowait=nowait, channel=channel) File "/home/aditya/.local/lib/python3.10/site-packages/kombu/entity.py", line 615, in _create_queue self.queue_declare(nowait=nowait, passive=False, channel=channel) File "/home/aditya/.local/lib/python3.10/site-packages/kombu/entity.py", line 643, in queue_declare ret = channel.queue_declare( File "/home/aditya/.local/lib/python3.10/site-packages/kombu/transport/virtual/base.py", line 523, in queue_declare return queue_declare_ok_t(queue, self._size(queue), 0) File "/home/aditya/.local/lib/python3.10/site-packages/kombu/transport/SQS.py", line 633, in _size resp = c.get_queue_attributes( File "/home/aditya/.local/lib/python3.10/site-packages/botocore/client.py", line 514, in _api_call return self._make_api_call(operation_name, kwargs) File "/home/aditya/.local/lib/python3.10/site-packages/botocore/client.py", line 938, in _make_api_call raise error_class(parsed_response, operation_name) botocore.exceptions.ClientError: An error occurred (InvalidClientTokenId) when calling the GetQueueAttributes operation: The security token included in … -
Send detecction to client in Real Time and diaply for client not work for me. using Django,React,Yolov5
i'am trying to get the precent of detection in real time,for every moment that is happen and then send it to client and display it,but it's not work for me. using django,react and yolov5 for detection. i'am using this fuction to get the detection in real,while i send only result i actully get this data and i see it, in the cliet ,but when i'am trying to get the precent of detection(0-1) it's not send the data for client . My goal is a function that send the data for client for every moment that have a detection and then i'll disply it for my client. views.py ` def stream(): cap = cv2.VideoCapture(source) model.iou=0.5 model.conf=0.15 while (True): ret, frame = cap.read() if not ret: print("Error: failed to capture image") break results = model(frame,augment=False,size=640) for i in results.render(): data=im.fromarray(i) data.save('demo.jpg') annotator = Annotator(frame, line_width=2, pil=not ascii) im0 = annotator.result() image_bytes = cv2.imencode('.jpg', im0)[1].tobytes() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + image_bytes + b'\r\n') cap.release() cv2.destroyAllWindows() def detection(): if __name__ == '__main__': p1 = Process(target = stream) p2 = Process(target = detection) p1.start() p2.start() p1.join() p2.join() def video_feed(request): return StreamingHttpResponse(stream(), content_type='multipart/x-mixed-replace; boundary=frame') def detection_percentage(request): return HttpResponse(detection()) Client using react const Streamvideo = () => … -
Null Session in the django-restful framework
Django rest framework I'm setting the session key once a user logins in request.session['id'] = 1 Then when I try to access it in the class view like id = request.session.get('id', 0) It is null [0] if the end-point call is made from the browser but it returns 1 if end-point call is from postman... I need your guidance... -
How to configure webpack to generate SuiteScript compatibile modules?
I am trying to use webpack to bundle a few libraries into my typescript suitelet. Netsuite expects suitescripts to follow amd modules pattern. If I use tsc tocompile my suitelet, I get correct syntax that looks this fragment: /** * * @NApiVersion 2.x * @NScriptType Suitelet */ define(["require", "exports", "N", "N/file"], function (require, exports, N_1, file_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.onRequest = void 0; var onRequest = function (context) { //my actual code here }; exports.onRequest = onRequest; }); The poblem is that the dependencies from node_modules are not bundled. So I have tried to use webpack for this, and webpack output differs: /** * * @NApiVersion 2.x * @NScriptType Suitelet */ define(["N", "N/file"], (__WEBPACK_EXTERNAL_MODULE__N, __WEBPACK_EXTERNAL_MODULE__Nfile) => { return (() => { //... some webpack internals goes here var __webpack_exports__ = {}; // This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk. (() => { __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "onRequest": () => (/* binding */ onRequest) // harmony imports goes here, cut for readability }); var onRequest = function onRequest(context) { //my actual code here }; … -
How to Update and Create at the same time?
I would like to create an object and once that is created I want to update an different object, not sure how to do that ? My View: class CreateUserClassQuestionRecord(UpdateAPIView, CreateAPIView): queryset = UserClassQuestionsRecord.objects.all() serializer_class = User_Class_Question_RecordSerializer permission_classes = [IsAuthenticated] def update(self, request, *args, **kwargs): user_inf =UserClassQuestionsRecord.objects.filter(user=self.request.user, question__singleclass_id =self.kwargs.get('pk')).all() for c in user_inf: if c : ClassAttempt.objects.filter(user=self.request.user, related_class_id=self.kwargs.get('pk')).update(is_first_time=False) else: pass My json : { "is_correct": "True", "xp_collected": 10, "user": 1, "question": 1, "selected_answer": 13 } The url : http://127.0.0.1:8000/api/class-record/new/13/ My Error message: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>` -
How to avoid fields that has null values automatically when rendering html
I want to not to display the null value fields in template.So How can i achieve this in django?Is there any functions available to do this. -
Post form redirect not retrieving resource django
I am sending a POST request to one of my views via fetch upon clicking a form's button in javascript. The POST request resolves and reaches a redirect, but the redirect does not render the corresponding view, rather the page remains on the same view. I have configured the urls with the views, name-spaced the application and I am overall unsure where I went wrong here, particularly because the resource is indeed returned from the redirect, but just not rendered. Here is my urls.py file: from email import policy from django.urls import path,re_path from . import views app_name = 'partyupapp' urlpatterns = [ path('', views.index, name='home'), #add create_event paths path('create_event/', views.create_event, name='create_event'), path('choose_venue/', views.choose_venue, name='choose_venue'), ] Here is my views.py file: def create_event(request): if request.method == 'POST': # Create form with request data in it form = PartyEventInfoForm(request.POST) # Check all validation criteria, is_valid implemented by default via UserCreationForm if form.is_valid(): # Process data return redirect('partyupapp:choose_venue') return render(request, 'PartyUpApp/create_event.html', {'form': form}) else: form = PartyEventInfoForm() return render(request, 'PartyUpApp/create_event.html', {'form': form}) def choose_venue(request): if request.method == 'POST': own_form = ChooseOwnVenueForm(json.load(request)['data']) # Check all validation criteria, is_valid implemented by default via UserCreationForm if own_form.is_valid(): # Process data return render(request,'PartyUpApp/hire_vendors.html') return render(request,'PartyUpApp/choose_venue.html', {'own_form': … -
The view products.views.get_product didn't return an HttpResponse object. It returned None instead. How to solve this error
shows the same error again and again...Can u please help me to solve this error url path("add-to-cart/<uid>/",add_to_cart,name="add_to_cart") html code <a href="{% url 'add_to_cart' product.uid %}?variant={{selected_size}}" class="btn btn-outline-primary"> <span class="text">Add to cart</span> <i class="fas fa-shopping-cart"></i> </a> def add_to_cart(request,uid): variant=request.GET.get('variant') product=Product.objects.get(uid=uid) user=request.user cart=Cart.objects.get_or_create(user=user, is_paid=False) cart_item=CartItems.objects.create(cart=cart,product=product) if variant: variant=request.GET.get('variant') size_variant=SizeVariant.objects.get(size_name=variant) cart_item.size_variant=size_variant cart_item.save() return HttpResponseRedirect(request.META.get('HTTP_REFFER')) else: return HttpResponseRedirect(request.META.get('HTTP_REFFER')) shows the same error again and again...Can u please help me to solve this error -
Heroku & AWS - Error while running '$ python manage.py collectstatic --noinput'
Trying to push my code from github to Heroku after setting up S3 for statics. I am using Django. I tried different solutions I found on here, but no success. Here are the different things I did. Removed whitenoise which apparently is incompatible with django-storages; I also tested the following combowhich returned no error. python manage.py collectstatic python manage.py test I did manage to push the code to heroku with $ heroku config:set DISABLE_COLLECTSTATIC=1 but obviousy statics are not there. Finally, a post suggested to run heroku run 'bower install --config.interactive=false;grunt prep;python manage.py collectstatic --noinput', but this only results in an error message for me C:\Program' is not recognized as an internal or external command,operable program or batch file. Code wise, I have a file called Settings, in which I have base.py, prod.py and dev.py. base.py import os from pathlib import Path import django_heroku import dj_database_url from decouple import config from dotenv import load_dotenv, find_dotenv # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent.parent # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "crispy_forms", 'main.apps.MainConfig', 'django_extensions', 'storages', 'import_export', 'django.contrib.sites', 'fontawesomefree', ] 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', ] … -
Issue with Paypal in AWS lightsail deployment
I have an PayPal standard check-out implemented in my Django template. Everything work fine on my local server. When I have deployed into a AWS lightsail instance (still using sandbox account) it doesn't work anymore. Paypal pop-up, shows but doesn't load. In my lighstail instance I use nginx and gunicorn. I would appreciate any hints. my nginx code is std default server { listen 80; listen [::]:80; listen 443; listen [::]:443; server_name 13.50.59.xx; location / { include proxy_params; proxy_pass http://127.0.0.1:8000/; } location /static/ { autoindex on; alias /home/ubuntu/NewBench/staticfiles/; } } -
Ajax post data don't arrive to Django
I am developing a Django application. I am trying using jquery and ajax for a POST request but I am not able to find the error. I am basically struggling to send the data from the frontend with ajax to the server. views.py def add_new_question_feedback(request, pk): if request.headers.get('x-requested-with') == 'XMLHttpRequest': question = Question.objects.get(id=pk) feedback = QuestionFeedback( question=question, user=request.user, text=request.POST.get('feedback'), feedback_choice=request.POST.get('feedback_choice')) feedback.save() feedback = serializers.serialize('json', [feedback]) return HttpResponse(feedback, content_type='application/json') models.py class QuestionFeedback(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) user = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE) text = models.TextField() feedback_choice = models.CharField( max_length=200) is_closed = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) template <div class="modal-header"> <h5 class="modal-title">${gettext( "Question Feedback" )} n° ${res[0].pk}</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <div class="form-group mt-3"> <label class="form-label">${gettext( "Feedback Type" )}</label> <select name="feedback_choice" id="feedback_choice" class="form-control" required=""> <option value="" selected="" disabled>${gettext( "Select Topic" )}</option> <option value="Wrong Question">${gettext( "Wrong Question" )}</option> <option value="Wrong Answer">${gettext( "Wrong Answer" )}</option> <option value="Other">${gettext( "Other" )}</option> </select> </div> <div class="form-group mt-3"> <label class="form-label">${gettext( "Feedback" )}</label> <textarea name="feedback" id="feedback" rows="10" class="form-control"></textarea> </div> <button type="button" class="btn btn-success mt-3" id="addFeedback"> ${gettext( "Add New Feedback" )} </button> <button type="button" class="btn btn-danger mt-3 ms-3" data-bs-dismiss="modal">${gettext( "Close" )}</button> </div> `; ajax function $("#addFeedback").on("click", function () { $.ajax({ type: "POST", url: "/quiz/add_new_question_feedback/" + questionBtnId, … -
Django IntegrityError : null value in column violates not-null constraint but there is a value in the request
I have a form that tries to add a record in a database using django. When trying to save into the database, i get the error IntegrityError: null value in column "aid" violates not-null constraint, but when I look at the request, I can clearly see a non-null value for the column 'aid' aid '10' uid '2' rid '13' action '' time '' table '' When I print the request.data inside views.py I can see all the values from the request: <QueryDict: {'aid': ['10'], 'uid': ['2'], 'rid': ['13'], 'action': [''], 'time': [''], 'table': ['']}> My question is why django cannot find the PK column> -
Current user does not show up in form from ModelForm whilst relationship has been established in Django
I have two models defined, a Test model and a User model. The Test model relates to the User model with a ForeignKey. The Test model has many different aspects to it, so I have truncated it, but I make a form of it with ModelForm. Then I call the form, and indeed all the entries show up, including a cell for User, however it shows no options or pre-selection for current user. What am I doing wrong? #User as rendered in form in browser: <select name="researcher" id="id_researcher"> <option value="" selected>---------</option> models.py from django.db import models from django.contrib.auth.models import (BaseUserManager, AbstractBaseUser) class User(AbstractBaseUser): is_active = models.BooleanField(default=True) def get_full_name(self): """ Return the first_name plus the last_name, with a space in between. """ full_name = "%s %s" % (self.first_name, self.last_name) return full_name.strip() @property def is_staff(self): "Is the user a member of staff?" return self.staff @property def is_admin(self): "Is the user a admin member?" return self.admin class Test(models.Model): researcher = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, related_name="researcher") views.py from django.shortcuts import render from django.contrib.auth import authenticate, login, logout from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from django.views.generic.edit import CreateView, UpdateView, DeleteView from database.forms import TestForm from database.models import User, Test # Create your … -
Django Many To Many Ordering
I have two tables Subjectlist and Day. Subject list is m2m in Day. So my problem is I'm creating school timetable. So for each days different subjects to be shown, when i add subjects on each days the order of subject is same. #Models.py class SubjectList(models.Model): subject_name = models.CharField(max_length=25) def __str__(self): return self.subject_name class Day(models.Model): day_name = models.CharField(max_length=15) subject_name = models.ManyToManyField(SubjectList) class_number = models.ForeignKey(AddClass, on_delete=models.CASCADE, null=True, blank=True) start_time = models.TimeField(null=True, blank=True) end_time = models.TimeField(null=True, blank=True) def __str__(self): return self.class_number.class_number #Views.py class TimeTableView(APIView): def get(self, request, id): class_number = AddClass.objects.get(id=id) day = Day.objects.filter(class_number=class_number.id) print(day) serializer = DaySerializer(day, many=True) return Response(serializer.data) I want to do like this Monday - English, maths, science, Social Science Tuesady - Maths, Social Science, Englih, Math's but i get like this Monday - English, maths, science, Social Science Tuesday- English, maths, science, Social Science both are in same order even if add subjects in different order.