Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Element of type <myclass> is not json serializable
class priceManage(object): def __init__(self,uid): self.uid = uid def getRealPrice(self): tot_price = 0 plist = e_cart.objects.filter(e_uid_id = self.uid, e_ordnum__isnull = True).select_related() for x in plist: tot_price += x.e_prodid.getRealPrice()*x.e_qta return float(tot_price) all done, but when i instance object and try to serialize with json i get Object of kind priceManage is not json serializable why f i return a float? So many thanks in advance -
How do I create a Django endpoint that receives JSON files?
I'm designing a Django endpoint that is supposed to receive a JSON file message from an API that sends texts. On the API, I'm supposed to include the endpoint (drlEndpoint) so that after a text is sent, the app endpoint can also receive a report in form of a JSON file. How do I design an endpoint that can receive the report? Here is the API... api_key = "" api_secret = "" # Get Bearer token = api_key + api_secret message_bytes = token.encode('ascii') base64_bytes = base64.b64encode(message_bytes) bearer = base64_bytes.decode('ascii') # Handle data and send to API enpoint post_dict = { 'unique_ref': '', 'clientId': '', 'dlrEndpoint': '', 'productId': '', 'msisdn': '', 'message': '', } data = json.dumps(post_dict) # converts data to json url = '' # set url headers = {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + bearer} # set headers r = requests.get(url=url, data=data, headers=headers) # make the request to the API endpoint my_data = r.json() # converts the request into json format print(my_data) # makes the request and prints to terminal -
Attribute Error in Django model Foreign Key
In My Django Project, there are two apps: Login and Company The error that am receiving in this is AttributeError: module 'login.models' has no attribute 'Country' Company App > models.py from django.db import models from login import models as LM class CompanyProfile(models.Model): full_name = models.CharField(max_length=255, unique = True) country = models.ForeignKey(LM.Country, on_delete=models.SET_NULL, null=True, blank=False) state = models.ForeignKey(LM.State, on_delete=models.SET_NULL, null=True, blank=False) def __str__(self): return self.full_name Login App > models.py class Country(models.Model): """List of Country""" name = models.CharField(max_length=50, unique= True, default='None') code = models.CharField(max_length=2, unique= True, primary_key=True, default ='NA') def __str__(self): return str(self.code) class State(models.Model): """List fo State""" region = models.CharField(max_length = 255, unique = True, primary_key=True, default='None') country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True, blank=False, default ='NA') def __str__(self): return self.region Here is test to check that weather is login is getting imported or not def test_import(): try: # import pdb; pdb.set_trace() importlib.find_loader('LM.Country') found = True except ImportError: found = False print(found) Answer is received stands to be True python3 manage.py shell >>> test_import() True Now on other stackoverflow blogs i checked i thought it could be of Circlular Import But i have already fixed that still am getting this error? Thanks in Advance Regards -
Cron for sending emails after 3 days in django
I dont have any knowledge about the cron. In my project once the task is assigned to employee email is sent to his mailid. If the employee does not complete the task within deadline I want to send the mail after every 3 days to complete the task. Can anyone give me I idea what I should do. The project is on my local environment, does it support or I should take server. -
How to extract data from django model
There is a django model with this field task_args. This field contains record like this ('test_user', 1, ['test'], 'id_001'). This field is a text field. How do I filter data from this model using this field I tried the following but this does not seem to work user = request.user.username num = 1 parsed_data = eval("['test']") id = "id_001" print(type(parsed_data)) args = f"{(user,num,parsed_data,id)}" print(args) task_id = list(TaskResult.objects.filter(task_args=args).values('task_id')) This results in an empty list. -
Convert nested query MySQL django
Im trying to convert this query from MySQL to Django, but I don't know how to do nested select in python, please, could you help me? SELECT zet.zone, SUM(CASE WHEN zet.`status` = 'available' THEN zet.total ELSE 0 END) AS `ge_available`, SUM(CASE WHEN zet.`status` = 'assigned' THEN zet.total ELSE 0 END) AS `ge_assigned`, SUM(CASE WHEN zet.`status` = 'on_going' THEN zet.total ELSE 0 END) AS `ge_on_going`, SUM(CASE WHEN zet.`status` = 'stopped' THEN zet.total ELSE 0 END) AS `ge_stopped` FROM (SELECT vhgz.zone zone, vhgz.status status, COUNT(*) total FROM view_historic_group_zone vhgz, (SELECT group_id gid, MAX(date_change) fe FROM historical_group WHERE date_change <= '2020-09-21 15:12:56' GROUP BY group_id) hg WHERE vhgz.date = hg.Fe AND vhgz.gid = hg.gid GROUP BY vhgz.zone, vhgz.status) zet GROUP BY zet.zone Model.py class viewhistoricgroupzone (models.Model): zone = models.CharField(max_length=50) date = models.DateTimeField() status = models.CharField(max_length=23, blank=True, null=True) gid = models.PositiveIntegerField() The result should be: {"zone":"Spain","available":0,"assigned":1,"on_going":15,"stopped":2} {"zone":"England","available":12,"assigned":4,"on_going":5,"stopped":1} {"zone":"Italy","available":2,"assigned":4,"on_going":12,"stopped":4} {"zone":"Germany","available":5,"assigned":8,"on_going":7,"stopped":3} -
Run django url in background inside windows 10
I'm new to django and trying to develop a system which requires to run a certain script in the background. if i'm using linux i can register this automatically to crontab. but what will be the process if i'm using windows 10? is there any way to automate the registration of tasks in task scheduler? Here are the example of link i'm accessing http://localhost/get/1 http://localhost/get/2 http://localhost/get/3 i want to run the following link asynchronous to each other. Thank you for suggestions and help -
Which plugin for Django autocompletion
I'd like to use autocompletion in my Django project but I don't know which plugin to choose. I have ModelMultipleChoiceField in my form like: tags = forms.ModelMultipleChoiceField( label=_("Etiquettes"), queryset=Tag.objects.all(), to_field_name="name", required=False, widget=forms.SelectMultiple(attrs={'class': "form-control form-custom"}) ) I'd like to change it into autocompletion. I know there is Typeahead and Django-autocomplete-light plugins but I don't know which one is better for my case. I want to create tag if it doesn't exist after typing it. I want a field like tags in StackOverflow question form but creating tags too. Thank you if anybody can help me. Best regards. -
Django Cloudinary - how do I supply the cloud name (except in the settings)?
I am building a django 3.1.1 app with a simple cloudinary setup for storing images. I get a weird error Must supply cloud_name in tag or in configuration although I did everything as stated in the package documentation: CLOUDINARY_STORAGE = { 'CLOUD_NAME': 'your_cloud_name', 'API_KEY': 'your_api_key', 'API_SECRET': 'your_api_secret' } The uploads work fine, the images are present in Cloudinary and I even got them to display on the page. Now this error just pops from time to time and I can't seem to find the reason why. -
Only Django Admin pages visible while rest of Site blank in production
Im trying to host my site on heroku on my localhost my project is fine with no issues , on deploying it all I get are blank pages (I inspected it and elements are shown but nothing is visible on webpage)apart from admin pages I installed all the necessary packages as I was deploying that is to say gunicorn and whitenoise as well as setting STATIC_ROOT and STATICFILES_STORAGE . I at first set DISABLE_COLLECTSTATIC = 1 and later set it to 0 when deploying, I have failed to see any error that might be causing the issue some of my files for context settings STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_dev')] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' urls from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from django.conf.urls import handler404 urlpatterns = [ path('admin/', admin.site.urls), path('users/', include('user.urls')), path('users/', include('django.contrib.auth.urls')), path('accounts/', include('allauth.urls')), path('', include('pages.urls')), path('store/', include('store.urls')), #path("djangorave/", include("djangorave.urls", namespace="djangorave")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #error handlers handler404 = 'store.views.error_404' #handler500 = 'store.views.my_custom_error_view' -
How can I connect a user model to a custom model in Django?
I have a student model with a one-to-one relationship to the built-in Django User model. My aim is to combine both forms in a single template for registration such that whenever I create a new student, the student object is automatically assigned a user by using Django post_save signals. Below are the code snippets: models.py from django.contrib.auth.models import User from django.db import models # Create your models here. class Student(models.Model): CURRENT_CLASS = ( ('1', 'Form 1'), ('2', 'Form 2'), ('3', 'Form 3'), ('4', 'Form 4'), ) user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) first_name = models.CharField(max_length=200, null=True) last_name = models.CharField(max_length=200, null=True) adm_num = models.IntegerField(null=True) form = models.CharField(max_length=1, choices=CURRENT_CLASS, null=True) def __str__(self): return '%s %s' % (self.first_name, self.last_name) forms.py from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms from .models import Student class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'password1', 'password2'] class StudentForm(ModelForm): class Meta: model = Student fields = '__all__' exclude = ['user'] views.py def signupPage(request): form = CreateUserForm() student_form = StudentForm() if request.method == 'POST': form = CreateUserForm(request.POST) student_form =StudentForm(request.POST) if form.is_valid() and student_form.is_valid(): user = form.save() username = form.cleaned_data.get('username') messages.success(request, 'Account was created for ' + username) return redirect('student:login') … -
Django Session: TypeError at /order/ Object of type Decimal is not JSON serializable
While trying to delete a session variable it throws a type error. Well I to tried print out the each variable and its type that I am storing in the session. But I didn't find any variable of type decimal. What is the issue here, why ain't it deleting the session variable? def checkout_address(request): form = AddressChoiceForm(request.user, request.POST or None) next_ = request.GET.get('next') next_post = request.POST.get('next') redirect_path = next_ or next_post or None if form.is_valid(): address_type = request.POST.get('address_type', 'shipping') address = Address.objects.get(id=request.POST.get('address')) print(address.id) request.session[address_type+'_address_id'] = address.id if is_safe_url(redirect_path, request.get_host()): return redirect(redirect_path) else: return redirect('orders:order') return redirect('orders:order') def order(request): cart = Cart(request) order = None address_form = AddressChoiceForm(request.user) shipping_id = request.session.get('shipping_address_id', None) billing_id = request.session.get('billing_address_id', None) order, created = Order.objects.get_or_create(user=request.user, ordered=False) if shipping_id: shipping_address = Address.objects.get(id=shipping_id) order.shipping_address=shipping_address del request.session['shipping_address_id'] if billing_id: billing_address = Address.objects.get(id=billing_id) order.billing_address=billing_address del request.session['billing_address_id'] if billing_id or shipping_id: order.save() return TemplateResponse( request, "orders/order.html", { 'address_form':address_form, 'order':order, 'cart':cart } ) Traceback Internal Server Error: /order/ Traceback (most recent call last): File "/home/duke/.local/share/virtualenvs/empowerment-FJkKHZxq/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/duke/.local/share/virtualenvs/empowerment-FJkKHZxq/lib/python3.8/site-packages/django/utils/deprecation.py", line 116, in __call__ response = self.process_response(request, response) File "/home/duke/.local/share/virtualenvs/empowerment-FJkKHZxq/lib/python3.8/site-packages/django/contrib/sessions/middleware.py", line 63, in process_response request.session.save() File "/home/duke/.local/share/virtualenvs/empowerment-FJkKHZxq/lib/python3.8/site-packages/django/contrib/sessions/backends/db.py", line 83, in save obj = self.create_model_instance(data) File "/home/duke/.local/share/virtualenvs/empowerment-FJkKHZxq/lib/python3.8/site-packages/django/contrib/sessions/backends/db.py", line 70, … -
ValueError: not enough values to unpack (expected 2, got 1) in Django Framework
I am beginner in django, I just starts learning how to load static files and all about static file. After setting whole code when I run the server I encounter with this error: `C:\Users\Lenovo\Documents\Django project\project3\fees\views.py changed, reloading. Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Lenovo\anaconda3\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\Lenovo\anaconda3\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Lenovo\anaconda3\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Lenovo\anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\Lenovo\anaconda3\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "C:\Users\Lenovo\anaconda3\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Lenovo\anaconda3\lib\site-packages\django\contrib\staticfiles\checks.py", line 7, in check_finders for finder in get_finders(): File "C:\Users\Lenovo\anaconda3\lib\site-packages\django\contrib\staticfiles\finders.py", line 282, in get_finders yield get_finder(finder_path) File "C:\Users\Lenovo\anaconda3\lib\site-packages\django\contrib\staticfiles\finders.py", line 295, in get_finder return Finder() File "C:\Users\Lenovo\anaconda3\lib\site-packages\django\contrib\staticfiles\finders.py", line 59, in __init__ prefix, root = root ValueError: not enough values to unpack (expected 2, got 1)` please tell me why I am getting this error and how can i solve it. Here is setting.py files """ Django settings for project3 project. Generated by 'django-admin startproject' using Django 3.1.1. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see … -
TypeError: Cannot read property'map' of undefined, I want to implement select option using map, but there is a problem
error code : TypeError: Cannot read property 'map' of undefined PatientInfoModal D:/test/pages/patient/PatientInfoModal.js:164 161 | </Form.Item> 162 | 163 | <Form.Item name={['patient', 'hospital']} label="Hospital" rules={[{ required: true }]}> > 164 | <Select placeholder="Select a Hospital" style={{ width:'150px' }}> | ^ 165 | {testplz.map(a => <Option>{a.name}</Option>)} 166 | </Select> 167 | </Form.Item> mycode.js : const doctorplz = { doctor } const [ whats, whatsdata ] = useState("doctor") const testplz = doctorplz[whats] <Select placeholder="Select a Hospital" style={{ width:'150px' }}> {testplz.map(a => <Option>{a.name}</Option>)} </Select> console.log(doctorplz) : {doctor: Array(4)} doctor: Array(4) 0: {d_code: 1, name: "test1", position: "RB", code_id: 1} 1: {d_code: 2, name: "test2", position: "LB", code_id: 2} 2: {d_code: 3, name: "test3", position: "ST", code_id: 2} 3: {d_code: 4, name: "test4", position: "RW", code_id: 1} length: 4 __proto__: Array(0) __proto__: Object I got the error despite entering the code correctly. I don't know what the hell is wrong. Also, the code below works fine. mycode2.js (Code that works) const namelist = { "01": [ { d_code: '1', name: 'test1' }, { d_code: '2', name: 'test2' }, { d_code: '3', name: 'test3' } ] } const [ data, setData ] = useState("01"); const Options = namelist[data]; <Select placeholder="Select a Doctor" style={{ width:'150px' }} > … -
Convert ReturnDict/Serializer.data to normal dictionary in django
In my django application I want to work on serializer.data thus there is a need to convert ReturnDict or OrderDict to normal dictionary. How can I do that ? For e.g. Here's the example data {'id': 75, 'kits': [OrderedDict([('id', 109), ('items', [OrderedDict([('id', 505), ('quantity', 6), ('product', 3)]), OrderedDict([('id', 504), ('quantity', 4), ('product', 1)]), OrderedDict([(' id', 503), ('quantity', 2), ('product', 6)]), OrderedDict([('id', 502), ('quantity', 2), ('product', 5)]), OrderedDict([('id', 501), ('quantity', 2), ('product', 4)])]), ('quantity', 2), ('kit', 10)]), OrderedD ict([('id', 110), ('items', [OrderedDict([('id', 510), ('quantity', 12), ('product', 3)]), OrderedDict([('id', 509), ('quantity', 8), ('product', 1)]), OrderedDict([('id', 508), ('quantity', 4), ('product', 6)] ), OrderedDict([('id', 507), ('quantity', 4), ('product', 5)]), OrderedDict([('id', 506), ('quantity', 4), ('product', 4)])]), ('quantity', 4), ('kit', 1)])], 'transaction_type': 'Return', 'transaction_date': ' 2020-09-24T06:16:02.615000Z', 'transaction_no': 1195, 'is_delivered': False, 'driver_name': '__________', 'driver_number': '__________', 'lr_number': 0, 'vehicle_number': '__________', 'freight_charges': 0, 've hicle_type': 'Part Load', 'remarks': 'to be deleted', 'flow': 1, 'warehouse': 1, 'receiver_client': 3, 'transport_by': 4, 'owner': 2} -
Django REST Framework: HyperlinkedModelSerializer: ImproperlyConfigured error
I am trying to serialize my Django models using the HyperlinkedModelSerializer class from Django REST Framework. My application is a dictionary application. I defined the serializer class for a Definition model, DefinitionSerializer, as follows: class DefinitionSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Definition fields = ["id", "definition", "expression"] The Definition model is defined as follows: class Definition(models.Model): definition = models.CharField(max_length=256) I am trying to return the serialized data in my IndexView as follows: class IndexView(APIView): definitions = Definition.objects.all() serializer = DefinitionSerializer(definitions, context={"request": request}, many=True) return Response(serializer.data) Accessing that view, however, returns the following ImproperlyConfigured error: Could not resolve URL for hyperlinked relationship using view name "expression-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. Does this error have to do with the fact that I am including slugs instead of primary keys in my URLs? For example, the URL associated with the "expression" field in the DefinitionSerializer is: app_name = "dictionary" path("define/<slug:slug>", views.ExpressionView.as_view(), name="expression") How can I make this work? -
Integrating normal HTML form with Django form
What I am trying to do is have a form that has this HTML: <form method="post" action=""> {% csrf_token %} <label>Pick a class:</label> <select id="schedClass" name="schedClass" > <option>Select one</option> {% for i in classes %} <option value="{{ i.id }}">{{ i.name }}</option> {% endfor %} </select> </select> {{ form }} <input type="submit" value="reload"> </form> The problem is that for some reason when I submit, the select schedClass doesn't appear in the link. I think it comes from the fact that it's integrated with a django form, but I have no idea. For clarification, what I am trying to do is have a form that creates an instance of a specific model, and one of the categories is schedClass which is a ManyToManyField, but I can't use a ModelForm since I need the items in the selections to be only ones that are also linked to the user with another ManyToMany. Is there anything to do? -
RecursionError at : maximum recursion depth exceeded while calling a Python object
I can't seem to find the problem in header.html which is leading to "RecursionError: maximum recursion depth exceeded while calling a Python object". base.html: {% load static %} <!DOCTYPE html> <html> <body> {% include 'header.html' %} {% include 'navbar.html' %} {% include 'dashboard.html' %} <div class="container-fluid"> {% block content %} {% endblock %} </div> {% include 'footer.html' %} </body> <!-- Bootstrap core JavaScript--> <script src="{% static 'vendor/jquery/jquery.min.js' %}"></script> <script src="{% static 'vendor/bootstrap/js/bootstrap.bundle.min.js' %}"></script> <!-- Core plugin JavaScript--> <script src="{% static 'vendor/jquery-easing/jquery.easing.min.js' %}"></script> <!-- Custom scripts for all pages--> <script src="{% static 'js/sb-admin-2.min.js' %}"></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> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/js/bootstrap.min.js" integrity="sha384-a5N7Y/aK3qNeh15eJKGWxsqtnX/wWdSZSKp+81YjTmS15nvnvxKHuzaWwXHDli+4" crossorigin="anonymous"></script> </html> dashboard.html: {% load static %} {% extends 'base.html' %} <head> <title>:: Welcome to CrmNXT ::</title> <!-- Custom fonts for this template--> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet"> <!-- Custom styles for this template--> <link href="{% static 'css/sb-admin-2.min.css' %}" rel="stylesheet"> </head> <body id="page-top"> <!-- Page Wrapper --> <div id="wrapper"> <!-- Sidebar --> <ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar"> <!-- Sidebar - Brand --> <a class="sidebar-brand d-flex align-items-center justify-content-center" href="#"> <div class="sidebar-brand-icon rotate-n-15"> <i class="fas fa-address-card"></i> </div> <div class="sidebar-brand-text mx-3">Welcome to NexCRM</div> </a> <!-- Divider --> <hr class="sidebar-divider my-0"> … -
Django keeps applying migrations
This is making me go insane: when I migrate, my django (3.1.1) completes the task, but seems to forgets about it. If I migrate again it will stop because it's trying to reapply the migrations. Example of the situation: I drop db.sqlite3 I drop everything inside app/migrations (excluded init) I run makemigrations: no problems. I run migrate: no problems. I run migrate again: fails (django.db.utils.OperationalError: table "django_content_type" already exists) Just to make sure I've executed "migrate --plan", confirming that it intends to apply the migrations it just performed. What am I missing here? Planned operations: contenttypes.0001_initial Create model ContentType Alter unique_together for contenttype (1 constraint(s)) auth.0001_initial Create model Permission Create model Group Create model User admin.0001_initial Create model LogEntry admin.0002_logentry_remove_auto_add Alter field action_time on logentry admin.0003_logentry_add_action_flag_choices Alter field action_flag on logentry contenttypes.0002_remove_content_type_name Change Meta options on contenttype Alter field name on contenttype Raw Python operation Remove field name from contenttype auth.0002_alter_permission_name_max_length Alter field name on permission auth.0003_alter_user_email_max_length Alter field email on user auth.0004_alter_user_username_opts Alter field username on user auth.0005_alter_user_last_login_null Alter field last_login on user auth.0006_require_contenttypes_0002 auth.0007_alter_validators_add_error_messages Alter field username on user auth.0008_alter_user_username_max_length Alter field username on user auth.0009_alter_user_last_name_max_length Alter field last_name on user auth.0010_alter_group_name_max_length Alter field name on group auth.0011_update_proxy_permissions … -
How to get date input from table created using for loop in django?
So I have passed a context from views.py to my html template. I have created a html table using 'For Loop' in the following way and also added a column with input date field. <table class="table"> <thead style="background-color:DodgerBlue;color:White;"> <tr> <th scope="col">Barcode</th> <th scope="col">Owner</th> <th scope="col">Mobile</th> <th scope="col">Address</th> <th scope="col">Asset Type</th> <th scope="col">Schhedule Date</th> <th scope="col">Approve Asset Request</th> </tr> </thead> <tbody> {% for i in deliverylist %} <tr> <td class="barcode">{{i.barcode}}</td> <td class="owner">{{i.owner}}</td> <td class="mobile">{{i.mobile}}</td> <td class="address">{{i.address}}</td> <td class="atype">{{i.atype}}</td> <td class="deliverydate"><input type="date"></td> <td><button id="schedulebutton" onclick="schedule({{forloop.counter0}})" style="background-color:#288233; color:white;" class="btn btn-indigo btn-sm m-0">Schedule Date</button></td> </tr> {% endfor %} </tbody> Now I would like to get that date element value in javascript, but its proving difficult since I am assigning a class instead of id(as multiple elements cant have same id). I tried in the following way but its not working. The console log shows no value in that variable. <script> //i is the iteration number passed in function call using forloop.counter0 function schedule(i){ var deldate = document.getElementsByClassName("deliverydate"); deldate2 = deldate[i].innerText; console.log(deldate2); //log shows no value/empty console.log(i); //log shows iteration number </script> -
How do I get all the input from the same form field in django? (The form field is in a loop in the HTML thus shows more than once)
I'm trying to get all the input from the same form field which displayed in the HTML twice since it's in a loop (as in this example). Is there a way I can do it? Below are the codes: HTML def home(request): nums = [[3, "", 2, 7, 5, 6, 1, 4, 9], [1, 4, 5, 2, 3, 9, 6, 7, 8], [6, 7, 9, 1, 4, 8, 2, 3, 5], [2, 1, 3, 4, 6, 5, 8, 9, 7], [4, 5, 6, 8, 9, 7, 3, 1, 2], [7, 9, 8, 3, 1, "", 4, 5, 6], [5, 2, 1, 6, 7, 3, 9, 8, 4], [8, 3, 7, 9, 2, 4, 5, 6, 1], [9, 6, 4, 5, 8, 1, 7, 2, 3]] context = {'nums': nums} if request.method == "POST": form = SForm(request.POST) context['form'] = form if form.is_valid(): num = form.cleaned_data.get('num') else: form = SForm() context['form'] = form context['range'] = range(9) return render(request, 's/home.html', context) Forms.py class SForm(forms.Form): num = forms.IntegerField(min_value=0, max_value=9, label=False) HTML.py {% block content %} <form method="POST" name="s_form"> {% csrf_token %} {% for row in nums %} <tr> {% for col in row %} {% if forloop.counter0|divisibleby:"9" %} <br> {% endif %} {% if … -
Error While using Qtest custom apis to create a test case
Hi I am working on of the product development where in I want to upload test cases remotely to the qtest tool with the help of the custom apis provided by the tool, I am able to login to the tool generate the authorization code, but when I call the api for uploading/creating a test case its not allowing me upload the test case I am following their official apis website to take the sample data and upload the same through postman by calling there apis but getting the below error My Post man body { "name":"An automation Test Case created via API", "properties":[ { "field_id":1695364, "field_value":710 }, { "field_id":1695363, "field_value":711 } ], "test_steps":[ { "description":"Open browser", "expected":"" }, { "description":"Access gmail.com", "expected":"Page is successfully loaded" }, { "description":"call another test case", "expected":"log in successfully", "called_test_case": { "id": 7372896, "approved": true } } ] } error in postman { "message":"null" } If Some one can please help me out with the problem -
What is the difference between request.GET.get('key', '') and request.GET.get('key)?
What is the difference between request.GET.get('key', '') and request.GET.get('key')? I thought dict.get() method's default option is None when it has not described. Then None and '' is different in Python grammar? -
category field it there in model as a foreignkey but then also it giving me this error
AttributeError: Got AttributeError when attempting to get a value for field category on serializer HelpTopicSerializer. The serializer field might be named incorrectly and not match any attribute or key on the QuerySet instance. Original exception text was: 'QuerySet' object has no attribute 'category'. class HelpTopicCategorySerializer(serializers.ModelSerializer): class Meta: model = HelpCategory fields = ('category', 'parent') class HelpTopicSerializer(serializers.ModelSerializer): category = HelpTopicCategorySerializer() #here category is foreignkey class Meta: model = HelpTopic fields = ('category', 'view_or_read', 'popular_topic', 'question', 'answer') @api_view(['GET']) @permission_classes((IsAuthenticated,)) @authentication_classes((TokenAuthentication,BasicAuthentication,SessionAuthentication)) def help_topic_list(request): help_topic = HelpTopic.objects.all() for i in help_topic: print(i.category) # try: # help_topic = HelpTopic.objects.all() # except HelpTopic.DoesNotExist: # return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': print(help_topic, "ggggggggggggggggg") serializer = HelpTopicSerializer(help_topic) return Response(serializer.data) -
drf-yasg - How to customize persistent auth token?
I am using drf-yasg to generate open API, what I want is once I have added the token for authentication it should be persistent and should not expire when user refreshes the page. Currently if user refreshes the page the token gets lost and user again needs to enter the token again and again after any single change.