Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to customize the toolbar of Summernote in django admin
I just need the link button of the summernote. How is this toolbar edited? I tried the documentation and felt no proper guiding. -
cant use emojionearea in django
I cant use emojionearea in a simple page in django, i have followed the basics steps, listed in their website: what i have done: 1.downloaded the zip from their github and copied both of these files into css and js folder 2.configure django static settings e.g add to url, add static dir, add url pattern 3.added the script written above. code: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>TODO</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'css/emojionearea.min.css' %}"> <link rel="stylesheet" href="{% static 'css/main.css' %}"> </head> <body> {% include 'navbar.html' %} {% block content %} {% endblock content %} <script> $(document).ready(function() { $("#mytextarea").emojioneArea(); }) </script> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <script src="{% static 'js/emojionearea.min.js' %}"></script> </body> </html> and this is the form text area i want to add the emoji to: {% csrf_token %} <div class="form-row"> <div class="col-12"> <label for="inputTask">Tweet:</label> <textarea class="form-control" placeholder="Enter Tweet:" name="tweet" id="mytextarea"></textarea> </div> <div class="col-10"> <label for="inputTime">Image:</label> <input type="file" class="form-control" placeholder="select image:" name="images"> </div> <div class="col-2" style="margin-top: 35px;"> <button type="submit" class="btn btn-outline-primary float-right">Add Tweet</button> </div> </div> </form> i have also tried putting textarea … -
Django: How to unable unlogged user get data other users but enable him have his own data linked to his session
I'm working on simple django project. In this project every reuser has his own data collection as usual we do in our projects but I want to enable unlogged users to have his own data linked with particular session. Off course their data are deleted when session expired but this is the cost of not being registered. I want to block possibility for unlogged user to get data of registered users by typing direct url. All tutorials i have found are obout @login_required decorator but it works only for registered users and doesn't let unlogged users to have his own temporary data. Maybe somebady can help my , give my a hint or suggestion where i can find something useful to solve this problem. Thanks for help -
BaseSerializer.__init__() got multiple values for argument 'instance'
I am new to Django so I have used serializer for the CRUD operations,but this error has come here's my function: def updateemp(request,id): Updateemp = EmpModel.objects.get(id=id) form = CRUDSerializer (request.POST,instance=Updateemp) if form.is_valid(): form.save() messages.success(request,'Record Updated Successfully...!:)') return render(request,'Edit.html',{"EmpModel":Updateemp}) can someone tell me the solution? -
Call ajax of `django-restframework` api from template and the server checks who calls this api
I use google auth login in django project with django-oauth-toolkit What I want to do is Call ajax of django-restframework api from template and the server checks who calls this api. For example, I can get if user is login or not {% if user.is_authenticated %} in template. so, I can call the api with the user information like this. var url = "http://localhost/api/check?id={{user.email}}" $.ajax({ method:"get", url:url .... with id query server can understand who calls this request. However in this method,id is written barely, so you can make the fake request. So, I guess I should make some access token or some other key. Is there any general practice for this purpose??? -
Django SystemCheckError: System check identified some issues:
Good day. Creating a project https://github.com/LeonidPrice/advertisementboard with Django REST framework I got the following error when starting the server: (All migrations are done) (board) D:\python_projects\board\board>python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Program Files\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "D:\python_projects\board\board\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "D:\python_projects\board\board\lib\site-packages\django\core\management\commands\runserver.py", line 134, in inner_run self.check(display_num_errors=True) File "D:\python_projects\board\board\lib\site-packages\django\core\management\base.py", line 558, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: ?: (captcha.recaptcha_test_key_error) RECAPTCHA_PRIVATE_KEY or RECAPTCHA_PUBLIC_KEY is making use of the Google test keys and will not behave as expected in a production environment HINT: Update settings.RECAPTCHA_PRIVATE_KEY and/or settings.RECAPTCHA_PUBLIC_KEY. Alternatively this check can be ignored by adding `SILENCED_SYSTEM_CHECKS = ['captcha.recaptcha_test_key_error']` to your settings file. WARNINGS: main.AdditionalImage: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the MainConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'. main.AdvUser: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the MainConfig.default_auto_field attribute to point to a … -
Display all User profiles, in Django template, liked by the currently logged-in User (under ManytoMany field)
I built a portal, where members can see other users' profiles and can like them. I want to show a page where the currently logged-in users can see a list of profiles only of the members they liked. The Model has a filed 'liked', where those likes of each member profile are stored: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') company = models.CharField(max_length=500, blank = True) city = models.CharField(max_length=100, blank = True) website = models.URLField(max_length=500, blank = True) liked = models.ManyToManyField(User, related_name='user_liked', blank=True) My views.py, and here I only show all members so on my template I can loop through each member in members... Including 'member.profile' details from the Profile model. @login_required def all_fav_members(request): users = User.objects.all context = {'members':users} return render(request, 'club/all_fav_members.html', context) I've tried many things, both under views.py and my HTML template, but I was not able to loop through all users associated with a specific Profile under the 'liked' field where that user is equal to request.user. I'm new to Django, hence trying multiple things. The outcome usually is I get the whole list of members, not the ones current user liked. One of the not working examples: {% if member.profile.liked.filter(id=request.user.id).exists()%} My template: … -
Django debug toolbar not showing view class name
I am using a django-debug-toolbar==3.4.0 with Django==4.0.5. Everything works except I see this on the debug toolbar: The expected string should be the class name: DashboardView not "backend_base.views.view". Tha class itself is very simple: class DashboardView(LoginRequiredMixin, NavBarMixin, TemplateView): template_name = 'dashboard.html' In the old version of the same project the result was exactly the classname. What am I missing? -
drf_yasg @swagger_auto_schema not showing the required parameters for POST Request
I am using django-yasg to create an api documentation. But no parameters are showing in the documentation to create post request. Following are my codes: After that in swagger api, no parameters are showing for post request to create the event model.py class Events(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(EventCategory, on_delete=models.CASCADE) name = models.CharField(max_length=250, null=True) posted_at = models.DateTimeField(null=True, auto_now=True) location = models.CharField(max_length=100, null=True) banner = models.ImageField(default='avatar.jpg', upload_to='Banner_Images') start_date = models.DateField( auto_now=False, auto_now_add=False, blank=True, null=True) end_date = models.DateField( auto_now=False, auto_now_add=False, blank=True, null=True) description = models.TextField(max_length=2000, null=True) completed = models.BooleanField(default=False) def __str__(self): return f'{self.name}' class Meta: verbose_name_plural = "Events" serializers.py class EventSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True, many=False) category = EventCategorySerializer(read_only=True, many=False) class Meta: model = Events fields = '__all__' views.py @api_view(['POST']) @permission_classes([IsAuthenticated]) @user_is_organization @swagger_auto_schema( request_body=EventSerializer ) def registerEvent(request): """ To Register an events, you must be an organization """ data = request.data print("==================") print(data) print("==================") try: Event = Events.objects.create( user = request.user, category=EventCategory.objects.get(category=data['category']), name=data['name'], location=data['location'], start_date=data['start_date'], end_date=data['end_date'], description=data['description'], completed=data['completed'], ) serializer = EventSerializer(Event, many=False) Event = Events.objects.get(id=serializer.data['id']) Event.banner = request.FILES.get('banner') Event.save() serializer = EventSerializer(Event, many=False) return Response(serializer.data) except: message = {'detail': 'Event with this content already exists'} return Response(message, status=status.HTTP_400_BAD_REQUEST) -
I Want to get 2 types of Events, that are, Past Events and Future Events from my Events Model in a Debating Society Website made using Django
I have made a Website for the Debating Society of our College using Django. I would like to have 2 types of events Past and Upcoming (Future) according to the date_of_competition, i.e., if the date and time of competition is past current date and time then return it in past events, and if the date and time of competition is in future of the current date and time then return it in future events Here are my views.py file and models.py file for events models.py from django.db import models class Format(models.Model): format_name = models.CharField(max_length=100, null=False, unique=True) def __str__(self): return self.format_name class Organiser(models.Model): organiser_name = models.CharField(max_length=140, null=False, unique=True) def __str__(self): return self.organiser_name class Event(models.Model): banner_image = models.ImageField(upload_to="events") event_name = models.CharField(max_length=150, null=False) organiser_of_event = models.ForeignKey(Organiser, on_delete=models.CASCADE) format_of_event = models.ForeignKey(Format, on_delete=models.CASCADE) date_of_event = models.DateTimeField(auto_now_add=False) registration_fees = models.IntegerField(default=0, help_text="Enter Registration Fees For The Event in Rupees") details = models.TextField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.event_name view.py from django.shortcuts import render from .models import Event # Create your views here. def events(request): context = { 'title': 'Events', 'events': Event.objects.all() } return render(request, 'main/Events.html', context) What logic should be written in order to get both future and past events from my … -
java.lang.ClassNotFoundException: solr.LatLonType when starting solr with a schema from django build_solr_schema
I want to connect a search functionality to Django. I use django-haystack and solr. with a newly created Solr core I get the following error when starting Solr with a new schema.xml generated from python manage.py build_solr_schema Caused by: java.lang.ClassNotFoundException: solr.LatLonType at java.net.URLClassLoader.findClass(URLClassLoader.java:445) ~[?:?] at java.lang.ClassLoader.loadClass(ClassLoader.java:588) ~[?:?] at java.net.FactoryURLClassLoader.loadClass(URLClassLoader.java:872) ~[?:?] at java.lang.ClassLoader.loadClass(ClassLoader.java:521) ~[?:?] at java.lang.Class.forName0(Native Method) ~[?:?] at java.lang.Class.forName(Class.java:488) ~[?:?] at java.lang.Class.forName(Class.java:467) ~[?:?] at org.apache.solr.core.SolrResourceLoader.findClass(SolrResourceLoader.java:527) ~[?:?] at org.apache.solr.core.SolrResourceLoader.newInstance(SolrResourceLoader.java:604) ~[?:?] at org.apache.solr.core.SolrResourceLoader.newInstance(SolrResourceLoader.java:598) ~[?:?] at org.apache.solr.schema.FieldTypePluginLoader.create(FieldTypePluginLoader.java:74) ~[?:?] at org.apache.solr.schema.FieldTypePluginLoader.create(FieldTypePluginLoader.java:43) ~[?:?] at org.apache.solr.util.plugin.AbstractPluginLoader.load(AbstractPluginLoader.java:144) ~[?:?] at org.apache.solr.schema.IndexSchema.readSchema(IndexSchema.java:531) ~[?:?] at org.apache.solr.schema.IndexSchema.<init>(IndexSchema.java:188) ~[?:?] at org.apache.solr.schema.ManagedIndexSchema.<init>(ManagedIndexSchema.java:119) ~[?:?] at org.apache.solr.schema.ManagedIndexSchemaFactory.create(ManagedIndexSchemaFactory.java:279) ~[?:?] at org.apache.solr.schema.ManagedIndexSchemaFactory.create(ManagedIndexSchemaFactory.java:51) ~[?:?] at org.apache.solr.core.ConfigSetService.createIndexSchema(ConfigSetService.java:342) ~[?:?] at org.apache.solr.core.ConfigSetService.lambda$loadConfigSet$0(ConfigSetService.java:253) ~[?:?] at org.apache.solr.core.ConfigSet.<init>(ConfigSet.java:49) ~[?:?] at org.apache.solr.core.ConfigSetService.loadConfigSet(ConfigSetService.java:249) ~[?:?] at org.apache.solr.core.CoreContainer.createFromDescriptor(CoreContainer.java:1550) ~[?:?] at org.apache.solr.core.CoreContainer.lambda$load$10(CoreContainer.java:950) ~[?:?] how can i fix my schema.xml? apache solr 9.0 django 4.0 -
Stripe payment intent throw invalid integer
I have been trying to generating stripe payment intent but I see this error of invalid Integer Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/asgiref/sync.py", line 472, in thread_handler raise exc_info[1] File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 42, in inner response = await get_response(request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 253, in _get_response_async response = await wrapped_callback( File "/usr/local/lib/python3.8/site-packages/asgiref/sync.py", line 435, in __call__ ret = await asyncio.wait_for(future, timeout=None) File "/usr/local/lib/python3.8/asyncio/tasks.py", line 455, in wait_for return await fut File "/usr/local/lib/python3.8/concurrent/futures/thread.py", line 57, in run result = self.fn(*self.args, **self.kwargs) File "/usr/local/lib/python3.8/site-packages/asgiref/sync.py", line 476, in thread_handler return func(*args, **kwargs) File "/usr/local/lib/python3.8/contextlib.py", line 75, in inner return func(*args, **kwds) File "/usr/local/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/views/generic/base.py", line 84, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/yacht-away/bookings/views.py", line 94, in post print(payment.create_payment_intent()) File "/yacht-away/bookings/payments.py", line 14, in create_payment_intent payment = stripe.PaymentIntent.create( File "/usr/local/lib/python3.8/site-packages/stripe/api_resources/abstract/createable_api_resource.py", line 22, in create response, api_key = requestor.request("post", url, params, headers) File "/usr/local/lib/python3.8/site-packages/stripe/api_requestor.py", line 122, in request resp = self.interpret_response(rbody, rcode, rheaders) File "/usr/local/lib/python3.8/site-packages/stripe/api_requestor.py", line 399, in interpret_response self.handle_error_response(rbody, rcode, … -
Django admin How to tract the user time-in and time-out?
I've been searching all day on how to track the users time-in and time-out of the user, I just want that if the user(employee permission) login ( in django admin) it will insert record/track same goes with if the user logout. is it possible to do it on django? -
Django DETAIL: Failing row contains (..., null)
Error - DETAIL: Failing row contains (6, 2022-06-18 09:50:32.722841+00, 2022-06-18 00:00:00+00, NE, something, something, null). I got 3 models: Patient => Hospitalization&Consults(ForeignKey=Patient), OneToMany. I know there, on "null" spot, must be the Patient ID, but I don t know how to get this ID. Models.py: class Patient(models.Model): NameandLastName = models.CharField(max_length = 50) ... class Consult(models.Model) Patient = models.ForeignKey(Patient, on_delete = models.CASCADE) simptoms = models.CharField(max_length = 50) option_pay = models.CharField(max_length = 40, choices = pay_method) ... Views.py class Consult(LoginRequiredMixin, CreateView): model = Consult template_name = 'Manage/ConsultAdd.html' form_class = forms.FromConsultAdd def form_valid(self, form): form.instance.autor = self.request.user messages.success(self.request, f"smth") return super().form_valid(form) I think I have to put smth on views, but idk what. -
How to solve Process 'ForkPoolWorker-1' pid:2133000 exited with 'signal 9 (SIGKILL)'?
I am using django, celery and xhtml2pdf to generate pdfs. Small size pdf are created but when pdf size gets larger and few images is added. I get following error. Process 'ForkPoolWorker-1' pid:2133000 exited with 'signal 9 (SIGKILL)' Can somebody help to solve this? -
Python Django unhashable type slice error while trying to paginate class based 'Category' list view
I am trying to create a 'Category' page that filters out posts by its category, everything is fine till I try to add pagination option to its class in 'views.py'. Here is the error: This is what I have in 'views.py': class CatListView(ListView): template_name = 'academy/category.html' context_object_name = 'catlist' paginate_by = 2 def get_queryset(self): content = { 'cat': self.kwargs['category'], 'posts': ContentPost.objects.filter(category__name=self.kwargs['category']) } return content def category_list(request): category = Category.objects.exclude(name='default') context = { 'category' : category, } return context and this is what I have in 'urls.py': path('academy/category/<category>/', CatListView.as_view(),name='academy-category'), I appreciate your help in advance... Thanks -
login() takes 1 positional argument but 2 were given using django
I dont know why i receiving this error login() takes 1 positional argument but 2 were given, ive just follow this tutorial that after sign-up it will login automatic https://www.csestack.org/django-sign-up-registration-form/ def login(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): print("test") user = form.save() user.refresh_from_db() user.first_name = form.cleaned_data.get('first_name') user.last_name = form.cleaned_data.get('last_name') user.contact_number = form.cleaned_data.get('contact_number') user.email = form.cleaned_data.get('email') user.save() insert = Customer( user=user, first_name=user.first_name, last_name=user.last_name, contact_number=user.contact_number, email=user.email ) insert.save() raw_password = form.cleaned_data.get('password1') users = authenticate(username=user.username, password=raw_password) login(request, users) return redirect('Homepage') else: form = SignUpForm() return render(request, 'mysite/login.html', {'form': form}) this is the traceback Traceback (most recent call last): File "C:\Users\clair\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\clair\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\clair\OneDrive\Desktop\Thesis\mysite\myapp\views.py", line 36, in login login(request, users) Exception Type: TypeError at /login/ Exception Value: login() takes 1 positional argument but 2 were given -
how to fetch latest record based on some paramter in django restframework
i am trying fetch latest record based on parameter but when use( latest(), last(), earliest(), order_by('-id')[0], latest('-id') )all this method in queryset then i got empty record, please help me out. @api_view(['GET']) @permission_classes((IsAuthenticated,)) def details(request): if request.method == 'GET': category=request.query_params.get('category') name=request.query_params.get('name') try: d=Employee.objects.filter(category=category,name=name).latest() response_data=EmployeeSerializer(d,many=True).data return JsonResponse({"message": "detail retrieval","error":False,"code":200,"results":{"totalItems":d.count(),"pageData":response_data,"totalPages":1,"currentPage":0}}, status=HTTP_200_OK) except: return JsonResponse({"message": "details not exist","error":True,"code":200,"results":{}}, status=HTTP_200_OK) -
Django - problem with writing to database
I have a problem, the urls form works but I can't see the records in url/admin, can I ask for help, thank you :D class Note(models.Model): """...""" notes = models.CharField(max_length=100, unique=True) description = models.TextField() class Meta: verbose_name = "Note" verbose_name_plural = "Notes" def __str__(self): return self.notes class NoteView(View): def get(self, request): if request.method == 'POST': textN = Note.objects.all().order_by('notes') form = NoteAddForm(request.POST) if form.is_valid(): form.save() return redirect('Files/menu') else: textN = NoteAddForm() return render(request, 'Files/note.html', {'textN': textN}) class NoteAddForm(forms.ModelForm): """New note add form""" class Meta: model = Note fields = '__all__' -
Postive and Negative Validation Check is Not Working In Django Forms
I am working this validation check in django , i have to check postiva values. I have values a,b,c,d if (a,b) also (c,d) positive value will not allowed, i wrote the code this way but do not know why is not checking the validation. I am working on django forms.py for i in range(count): a = int(self.data.get(f'runtime_set-{i}-a') or 0) b = int(self.data.get(f'runtime_set-{i}-b') or 0) c = int(self.data.get(f'runtime_set-{i}-c') or 0) d = int(self.data.get(f'runtime_set-{i}-d') or 0) if a ==b==c==d: continue if (a + b) > 0 + (c + d) > 0: raise ValidationError( "When A '{a}' , B '{b}' is postive then C '{c}' and d'{d}' positive value is not allowed ") -
Foreign key is not assigned to a model in database
I recently started learning django and was making a CRM. models.py: class Complaint(models.Model): SOURCE_CHOICES=( ('email','E-mail'), ('call','Call'), ('ticket','Ticket') ) store_name=models.CharField(max_length=20) store_contact_no=models.IntegerField(max_length=10) store_id=models.CharField(max_length=7) source=models.CharField(choices=SOURCE_CHOICES, max_length=10) agent=models.ForeignKey("Agent", null = True, blank = True, on_delete=models.SET_NULL) category=models.ForeignKey("Category", related_name="complaints", null = True, blank = True, on_delete=models.SET_NULL) description = models.TextField() customer = models.ForeignKey("Customer", null = True, blank = True, on_delete=models.SET_NULL) def __str__(self): return f"{self.store_name} {self.store_id}" class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.user.username forms.py class CustomerComplaintForm(forms.ModelForm): class Meta: model = Complaint fields = ( 'store_name', 'store_id', 'store_contact_no', 'description', ) views.py class CustomerComplaintCreateView(OwnerCustomerAndLoginRequiredMixin, generic.CreateView): template_name = "customercomplaint_create.html" form_class = CustomerComplaintForm def get_success_url(self): return "/complaints" def form_valid(self, form): complaint = form.save(commit=False) complaint.Customer = self.request.user.username complaint.source = 'ticket' complaint.save() return super(CustomerComplaintCreateView, self).form_valid(form) html template: {% extends "base.html" %} {% load tailwind_filters %} {% block content %} <div class="max-w-lg mx-auto"> <a class="hover:text-blue-500" href="/complaints">Go back to complaints </a> <div class="py-5 border-t border-gray-200"> <h1 class="text-4xl text-gray-800"> Create a new complaint </h1> </div> <form method='post' class="mt-5"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="w-full bg-blue-500 text-white hover:bg-blue-600 px- 3 py-2 rounded-md">Create</button> </form> </div> {% endblock content %} The problem here is that, the source field gets filled in the database with Ticket as intended. But the 'Customer' field is not populated … -
I want to get datatables checkbox data from html template to views.py in django
I have used this example (https://jsfiddle.net/snqw56dw/3182/) to get checkboxes on my html table. I am getting the selected boxes data via the datatable script but I need to send this data to views.py on submission. I have used AJAX but it seems that I have been doing something wrong. Could you please help. Javascript on html: $(document).ready(function() { var table1 = $('#pgnum').DataTable({ 'columnDefs': [ { 'targets': 0, 'checkboxes': { 'selectRow': true } } ], 'select': { 'style': 'multi' }, 'order': [[1, 'asc']] }); // Handle form submission event $('#eg').on('submit', function(e){ var arr = []; var form = this; var rows_selected = table1.column(0).checkboxes.selected(); // Iterate over all selected checkboxes $.each(rows_selected, function(index, rowId){ // Create a hidden element arr.push(rowId); }); $.ajax({ type: "POST", url: "{% url 'add_user_eng' %}", data: {arr: 'arr'}, }); }); }); urls.py url(r'^eng_edit_admin/eng_add_user', views.add_user_eng, name='add_user_eng'), views.py def add_user_eng(request): token = request.session['eng_id'] eng_id = str(token) user_list = User.objects.all() if request.method == 'POST': print("HELLO") print(request.POST.getlist('data[]')) return render(request, 'main/add_user_to_engagement.html',{'user_list':user_list}) form id="eg" I am getting an empty list even when I submit or reload the page. Any sort of help is appreciated. Thank you -
Django save on model
I just want that it will automatic compute when it save on the database class Order(models.Model): quantity = models.IntegerField(null=True, blank=True) price = models.IntegerField(null=True, blank=True) total_price = models.IntegerField(null=True, blank=True) def save(self, *args, **kwargs): self.total_price = self.price * self.quantity return (Order, self).save(*args, **kwargs) the error i received is 'tuple' object has no attribute 'save' -
Python django parallel process large amount of data
In my order models, I have around 5M dummy records, I am calculating these and pushing to another database. It is working great but very slow ! Coz, there mazzine amount of fake data. I am writing a django command to this and trying to split all the records in multiple process, al that It can finish quickly. from django.core.management.base import BaseCommand, CommandError from multiprocessing.pool import Pool from multiprocessing import Manager from order.models import Order class Command(BaseCommand): help = 'Scrape all the site parrally..' def handle(self, *args, **options): order_count = Order.objects.all().count() for ord in Order.objects.all(): calculate_n_push(ord) Can anyone advice me what could be the best way to handle this? -
How to check if the object is assigned to another object | Django
I am working on a django case like below: models.py class Room(models.Model): name = models.CharField("Room No.",max_length=200) class Meta: verbose_name_plural = "Room" def __str__(self): return self.name class Student(models.Model): name = models.CharField("name",max_length=200) father_name = models.CharField("father Name",max_length=200) cell_no = models.CharField("cell No",max_length=200) address = models.CharField("address",max_length=500) room = models.ForeignKey(Room, on_delete=models.CASCADE, null=True, blank=True, related_name='all_rooms') class Meta: verbose_name_plural = "Student" def __str__(self): return self.name views.py def room(request): allrooms= Room.objects.all() form = RoomForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() messages.success(request, "Room added successfully.") return redirect('/room') context = {'allrooms':allrooms, 'form':form} return render(request, 'room.html', context) In templates in room.html I want to show the status Vacant/Occupied based on the fact if a room is assigned to some student or not. I have the following code in template but it shows 'Vacant' status for all rooms. <table id="example1" class="table table-bordered table-striped"> <thead> <tr> <th>Room</th> <th class="text-center">Status</th> <th class="text-center">Action</th> </tr> </thead> <tbody> {% for room in allrooms %} <tr> <td>{{ room.name }}</td> <td class="text-center"> {% if room.student_set.all %} <small class="badge badge-danger">Occupied</small> {% elif not room.student.all %} <small class="badge badge-success">Vacant</small> {% endif %} </td> <td class="text-center"><a href="{% url 'updateroom' room.id %}"><i class="fas fa-edit"></i></a></td> </tr> {% endfor %} </tbody> </table> Please help someone to show he status of the room.