Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Do Model Tree Transvaal
I'm using django-mptt django library in my django models to store hierarchical data in a database. I have built an accounting api whereby when defining accounts there is are root,parent and children accounts for instance a root account can be Assets then Cash Account will be categorized as an Asset account. My question was if using this library will cost me especially performance wise.If someone has used it please advice. Below is an illustration of how my model looks like: class Account(MPTTModel): """ Represents an account An account may have a parent, and may have zero or more children. Only root accounts can have an account_type, all child accounts are assumed to have the same account_type as their parent. An account's balance is calculated as the sum of all of the transaction Leg's referencing the account. Attributes: uuid (SmallUUID): UUID for account. Use to prevent leaking of IDs (if desired). name (str): Name of the account. Required. parent (Account|None): Parent account, none if root account code (str): Account code. Must combine with account codes of parent accounts to get fully qualified account code. account_type (str):Also identified as account classification - Type of account as defined by :attr:`Account.TYPES`. Can only be … -
Djanfo Function based views return didn't return an HttpResponse object Error
I'm working on a project using python(2.7) and Django(1.10) in which I'm rendering a template with context data after user login but it return an error as: The view dashboard.views.home didn't return an HttpResponse object. It returned None instead. Here's my views.py: def home(request): user_type = user_id = '' try: user_id = request.session['user_id'] user_type = request.session['user_type'] except Exception as e: return redirect(mainlogin) if user_type == 'admin': unread_orders = CustomerOrder.objects.filter(status=0, visible_flag=1) complete_orders = CustomerOrder.objects.filter(status=2, visible_flag=1) active_drivers = User_table.objects.filter(user_type='driver', status=1, approval_status=1, is_active=True) pending_orders = CustomerOrder.objects.filter(Q(status=0) | Q(status=1) | Q(status=4)) return render(request, "index.html", {'unread_orders': unread_orders, 'active_drivers': active_drivers, 'pending_orders': pending_orders, 'complete_orders': complete_orders}) elif user_type == 'driver': unread_orders = CustomerOrder.objects.filter(driver_id=user_id, driver_order_status=0, visible_flag=1) complete_orders = CustomerOrder.objects.filter(driver_id=user_id, driver_order_status=2, visible_flag=1) active_drivers = '' pending_orders = CustomerOrder.objects.filter(driver_id=user_id).filter( Q(driver_order_status=0) | Q(driver_order_status=1) | Q(driver_order_status=4)) return render(request, "index.html", {'unread_orders': unread_orders, 'active_drivers': active_drivers, 'pending_orders': pending_orders, 'complete_orders': complete_orders}); What can be wrong here? Thanks in advance! -
To fetch Facebook analytics data and display it in my Dashboard
I'm working on a dashboard for a startup.What I'll have is a dedicated page on that dashboard which is a facebook login page from which I'll be directed to the page where i get all the analytics of his/her company apps. I want to display facebook analytics data into the dashboard. Have searched lots of websites for the same but didnt get any output which help me out. Is there any way by which i can access the analytics data from facebook ? -
Gitlab Django - How to install chromedriver for splinter django test suite?
I am using splinter for my Django functional tests. All functional tests are working locally without fail. But as as soon, as I push my project on my gitlab repository and the pipeline runs through all of them, all django tests fail because of a missing chromedriver. For my local machine, I refered to this site: https://splinter.readthedocs.io/en/latest/drivers/chrome.html But this didn't work with my pipeline script. Therefore I searched various methods, but I never found something specifically for splinter. Can someone explain me how to properly set up a headless chrome for Django pipeline testing on Gitlab? -
Django Order_by Not working on FloatField
Order_by not working in FloatField type Django models.py class CourseTrack(models.Model): category = models.ForeignKey(CourseCategory) course_id = CourseKeyField(max_length=255, db_index=True) tracks = models.FloatField(null=True, blank=True, default=None) active = models.BooleanField(default=True) class Meta(object): app_label = "course_category" def __unicode__(self): return str(self.course_id) I added here order_by(), as you can see but its not working. view.py def get_popular_courses_ids(): popular_category_id = CourseCategory.objects.filter(category='Popular') popular_courses_ids = CourseTrack.objects.values('course_id').filter(category=popular_category_id).order_by('tracks') course_id_list = [] for course_id in popular_courses_ids: course_id_list.append(course_id['course_id']) return course_id_list -
How to pass dynamically data into the xml tags
I have some xml/soap packs and i'd like to able to pass some data dynamically in some tags for example. I have the following xml packet. Payload = '''<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> <BankAccountType>ChequeAccount</BankAccountType> <AccountNumber>0495028198</AccountNumber> </s:Body>\n</s:Envelope> ''' Instead of hardcoding these i'd like to able to have something like this so that from postman i can inject directly inject some params such as bank_acc_type and account_number. bank_acc_type = request.POST.get('bank_acc_type') account_number = request.POST.get('account_number') Payload = '''<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> <BankAccountType>{account_type}</BankAccountType> <AccountNumber>{account_number}</AccountNumber> </s:Body>\n</s:Envelope> '''.format(bank_acc_type=bank_acc_type, account_number=account_number) However, this solution of mine is not working.While debugging, bank_acc_type is taking None as well as account_number. Can someone know a better way of solving this? -
difference between two querysets django
i have two querysets and i want to get the difference between them and pass them in one query to use it in my view and display to my template for price_date in pkg.prices_dates.all(): for territory in price_date.territory.all(): territory result: United Kingdom Belgium for territory in pkg.territories.all(): territory result: Belgium Canada France United Kingdom i want to get Canada France def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) data.update({ 'territory_not_selected':##### }) -
Django SelectMultiple widget in forms-How to have multiple values as initial selected data?
Have really been struggling with this one.I have a ModelForm to edit a Pizza object and one field is a Toppings postgres ArrayField. I'm using crispyforms. I want all the values that other users have entered into the ArrayField to be choices and to have the ones this user has already selected as initial values. I'm able to render all the choices correctly. But can only get 1 initial value to have the selected attribute on its option ie: <option value="Mushroom" selected="selected">Mushroom</option>. It won't let me pass a list or tuple in as self.initial['toppings'] = ['Mushroom','Tomato'], only a string self.initial['toppings'] = 'Mushroom' Anyone know how to fix this so I can pass in multiple selected choices as initial value for the form? Model looks like: def pizza(models.Model): toppings = django.contrib.postgres.fields.ArrayField(models.CharField(max_length=60), default=list, null=True, blank=True) Form looks like: class EditPizzaFormCrispy(forms.ModelForm): name = forms.CharField(max_length=30) def __init__(self, pizza, restaurant, *args, **kwargs): super(EditPizzaFormCrispy,self).__init__(*args,**kwargs) # First get all the choices toppings_query = restaurant.values_list('toppings',flat=True).distinct() toppings_choices_set = set([]) for i in topping_query: for elem in i: if elem not in ['',[],['']]: toppings_choices_set.add(elem) toppings_choices = [] for elem in toppings_choices_set.append((elem, elem) # Now set the widget self.fields['toppings'].widget = forms.SelectMultiple(attrs={ 'placeholder':'Choose Toppings', 'class': 'multi-select-input' 'multiple':'multiple', choices=toppings_choices}) # Here's … -
Unable to install ldap library on python3.6
Hi i am unable to install ldap library in python 3.6. Command used is: pip install python-ldap Error: pip install python-ldap Collecting python-ldap pip-install-snxkbc\python-ldap\ Using cached https://files.pythonhosted.org/packages/7f/1c/28d721dff2fcd2fef9d55b40df63a00be26ec8a11e8c6fc612ae642f9cfd/python-ldap-3.1.0.tar.gz Requirement already satisfied: pyasn1>=0.3.7 in c:\users\dm050767\python27\lib\site-packages (from python-ldap) (0.4.4) Requirement already satisfied: pyasn1_modules>=0.1.5 in c:\users\dm050767\python27\lib\site-packages (from python-ldap) (0.2.2) Building wheels for collected packages: python-ldap Running setup.py bdist_wheel for python-ldap ... error Complete output from command c:\users\dm050767\python27\python.exe -u -c "import setuptools, tokenize;file='c:\users\dm050767\appdata\local\temp\pip-install-snxkbc\python-ldap\setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" bdist_wheel -d c:\users\dm050767\appdata\local\temp\pip-wheel-kgoem3 --python-tag cp27: running bdist_wheel running build running build_py creating build\lib.win32-2.7 copying Lib\ldapurl.py -> build\lib.win32-2.7 copying Lib\ldif.py -> build\lib.win32-2.7 creating build\lib.win32-2.7\ldap copying Lib\ldap\async.py -> build\lib.win32-2.7\ldap copying Lib\ldap\asyncsearch.py -> build\lib.win32-2.7\ldap copying Lib\ldap\cidict.py -> build\lib.win32-2.7\ldap copying Lib\ldap\compat.py -> build\lib.win32-2.7\ldap copying Lib\ldap\constants.py -> build\lib.win32-2.7\ldap copying Lib\ldap\dn.py -> build\lib.win32-2.7\ldap copying Lib\ldap\filter.py -> build\lib.win32-2.7\ldap copying Lib\ldap\functions.py -> build\lib.win32-2.7\ldap copying Lib\ldap\ldapobject.py -> build\lib.win32-2.7\ldap copying Lib\ldap\logger.py -> build\lib.win32-2.7\ldap copying Lib\ldap\modlist.py -> build\lib.win32-2.7\ldap copying Lib\ldap\pkginfo.py -> build\lib.win32-2.7\ldap copying Lib\ldap\resiter.py -> build\lib.win32-2.7\ldap copying Lib\ldap\sasl.py -> build\lib.win32-2.7\ldap copying Lib\ldap\syncrepl.py -> build\lib.win32-2.7\ldap copying Lib\ldap__init__.py -> build\lib.win32-2.7\ldap creating build\lib.win32-2.7\ldap\controls copying Lib\ldap\controls\deref.py -> build\lib.win32-2.7\ldap\controls copying Lib\ldap\controls\libldap.py -> build\lib.win32-2.7\ldap\controls copying Lib\ldap\controls\openldap.py -> build\lib.win32-2.7\ldap\controls copying Lib\ldap\controls\pagedresults.py -> build\lib.win32-2.7\ldap\controls copying Lib\ldap\controls\ppolicy.py -> build\lib.win32-2.7\ldap\controls copying Lib\ldap\controls\psearch.py -> build\lib.win32-2.7\ldap\controls copying Lib\ldap\controls\pwdpolicy.py -> build\lib.win32-2.7\ldap\controls copying Lib\ldap\controls\readentry.py -> build\lib.win32-2.7\ldap\controls copying Lib\ldap\controls\sessiontrack.py -> build\lib.win32-2.7\ldap\controls copying Lib\ldap\controls\simple.py … -
django serializing model with foreign key (Post and get)
I have 2 models in django class Media(models.Model): path = models.TextField(blank=True, null=True) class Upload(models.Model): date = models.DateField(null=True, blank=True) brand = models.ForeignKey(NewBrand, models.DO_NOTHING, null=True, blank=True) user = models.ForeignKey(User, models.DO_NOTHING, null=True, blank=True) pos = models.ForeignKey(Pos, models.DO_NOTHING, null=True, blank=True) img = models.ForeignKey(Media, models.DO_NOTHING, null=True, blank=True) i have the img field in Media model which is a foreign key to Media model i make these 2 serializers for the media and upload models class MediaSerializer(serializers.ModelSerializer): class Meta: model=Media fields = '__all__' class UploadsSerializer(serializers.ModelSerializer): img = MediaSerializer() class Meta: model = Upload fields = '__all__' def create(self, validated_data): media_data = validated_data.pop('img') upload = Upload.objects.create(**validated_data) Media.objects.create(upload=upload, **media_data) return upload and here is the view , i am using generics from the django rest framework to make a view for post and get request class UploadCreateAPIView(generics.CreateAPIView,generics.ListAPIView): queryset = Upload.objects.all() serializer_class = UploadsSerializer The get request is working fine and the post request is working too but it is giving null for the img field as below: { "id": 31, "img": null, "date": "2018-12-06", "brand": 1, "user": 7, "pos": 2 } but i want to get this response back from POST Request: { "id": 26, "img": { "id": 2, "path": "https://scontent.fbey14-1.fna.fbcdn.net/v/t1.0-9/15036559_10157781576890022_1074176357671620237_n.jpg?_nc_cat=107&_nc_ht=scontent.fbey14-1.fna&oh=e40600d35f8f6e803b7cd7a23fd53de4&oe=5C6C4596" }, "date": "2018-12-05", "brand": 1, "user": 4, … -
Is there any tutorial or guide of Fabric version 2.4?
everyone. I am developing django website with django 1.11, python 3.6. In deploying django, I want to use Fabric. I searched Fabric tutorial and guide. But they all use Fabric version 1.x. In recent, Fabric has become version 2.4. Fabric version 2.4 API is incompatible with version 1.x API. Official document is hard for me. I want tutorial or example code. Is there any tutorial or guide of Fabric version 2.4? Thanks. -
Django CSRF verification failed even after adding csrf_token tag inside the form html
I'm working on a project using Python(2.7) and Django(1.10) in which I need submit the login form but it returns an error on submission. Note: I have searched a lot of questions tried various answers but in most cases the {% csrf_token %} is missing from the <form> HTML but in my case, I'm using this also, that's why don't mark this question duplicated, please! Here's what I have tried: from form.html: <form class="fields-signup" action="{% url 'mainlogin' %}" method="post"> {% csrf_token %} <h1 class="text-center">Sign In</h1> <div class="form-group"> <input class="user-name form-control" type="text" name="username" placeholder="User name"> </div> <div class="form-group"> <input class="password form-control" type="password" placeholder="Password" name="password"> </div> <input type="submit" class="btn siteBtn" value="Sign In"> <!-- <a href="#" class="btn siteBtn" >Sign Up</a> <p class="text-center">Don’t Have an account? <a href="#">Signup</a></p> --> <!--popup-forget-password--> <div class="col-sm-12"> <button type='button' class="forget-password-btn" data-toggle="modal" data-target="#popUpWindow">Forgot Password</button> <!--forget-password-end--> <div class="col-sm-12 register"> <a class="register-driver-btn" data-toggle="modal" data-target="#popUpWindow_register">Register Driver?</a> </div> </div> </form> from urls.py: url(r'^$', views.home, name="home"), from views.py: if request.method == "GET": try: temp = get_template('login.html') result = temp.render(Context({'context': RequestContext(request)})) return HttpResponse(result) Also, I have included the csrf middleware in my settings.py. what can be wrong here? Thanks in advance! -
Why doesn't django accept my custom filter with any name except 'cut'?
Guys I see wired issue with django. I am trying to create my own custom filter and it only works if I name it "cut" but it will never work with any other names: from django import template register = template.Library() @register.filter(name='cut') def removeText(value, arg): return value.replace(arg,'') and this is how I call it in the template <h1>{{text|cut:"hello"}}</h1> This is the error message -
Django Wagtail - Draftail - Multiple Color Highlighter
Django Wagtail - Draftail - Multiple color highlighter How do I implement a multiple color highlight feature in Django wagtail CMS with draftail? I can't get the inline text in the editor to correspond to the styles i chose after saving a page. The colors in the editor dissapears. There must be something wrong when wagtail reads the style from database. -
Find parent data using Django ORM
I have 3 tables AllTests ReportFormat Parameter AllTests has reportFormat as ForeignKey with one to one relation. class AllTests(models.Model): id=models.AutoField(primary_key=True) name=models.CharField(max_length=200) reportFormat=models.ForeignKey(ReportFormat) ..... ..... class Meta: db_table = 'AllTests' Parameter table has reportFormat as ForeignKey with one too many relations. Means one report format has many parameters. class Parameter(models.Model): id=models.AutoField(primary_key=True) name=models.CharField(max_length=200) reportFormat=models.ForeignKey(ReportFormat) ..... ..... class Meta: db_table = 'AllTests I want to make a query on the parameter model that return parameter data with the related test data. Please suggest me a better way for the same. -
Django TypeError: annotate() missing 1 required positional argument: 'self'
I want to subtract values of annotation in my views: I have tried this: qs = Stockdata.objects.filter(User=self.request.user, Company=company_details.pk, Date__gte=selectdatefield_details.Start_Date, Date__lte=selectdatefield_details.End_Date) qs = qs.annotate( sales_sum = Coalesce(Sum('salestock__Quantity'),0), purchase_sum = Coalesce(Sum('purchasestock__Quantity_p'),0) ) qs = QuerySet.annotate( difference = ExpressionWrapper(F('sales_sum') - F('purchase_sum'), output_field=DecimalField()) ) But getting this error now TypeError: annotate() missing 1 required positional argument: 'self' Do anyone have any idea what this error indicates?? -
Make mysql connection from django using option no-auto-rehash
Whenever I am connecting to remote mysql server using django, server takes lot of time for making connection. When I connect from bash using -A option it connects instantly as it does not load the metadata for the database I am connecting to. Is there a way in django to implement the same? -
Relation does not exist after extend existing User model
I've follow django docs to extend existing user model. I've done makemigrations and migrate already.When i try to get the either client_id or client_site_id , it return error. Is there anything missing or any error in my code? Here is my models.py: class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) client_id = models.ForeignKey(Client, models.DO_NOTHING, db_column='Client_Id') client_site_id = models.ForeignKey(ClientSite, models.DO_NOTHING, db_column='Client_Site_Id') Here is my views.py- to get the client_id user = User.objects.get(username='James') info = user.userprofile.client_id Error: File "C:\Python\Python36\lib\site-packages\django\db\models\fields\related_descriptors.py" in __get__ 392. rel_obj = self.related.get_cached_value(instance) File "C:\Python\Python36\lib\site-packages\django\db\models\fields\mixins.py" in get_cached_value 13. return instance._state.fields_cache[cache_name] During handling of the above exception ('userprofile'), another exception occurred: File "C:\Python\Python36\lib\site-packages\django\db\backends\utils.py" in _execute 85. return self.cursor.execute(sql, params) The above exception (relation "customers_userprofile" does not exist LINE 1: ...entId", "customers_userprofile"."Client_Site_Id" FROM "customers... ^ ) was the direct cause of the following exception: File "C:\Python\Python36\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "C:\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\client\views.py" in View 136. info = user.userprofile.client_id File "C:\Python\Python36\lib\site-packages\django\db\models\fields\related_descriptors.py" in __get__ 400. rel_obj = self.get_queryset(instance=instance).get(**filter_args) File "C:\Python\Python36\lib\site-packages\django\db\models\query.py" in get 393. num = len(clone) File "C:\Python\Python36\lib\site-packages\django\db\models\query.py" in __len__ 250. self._fetch_all() File "C:\Python\Python36\lib\site-packages\django\db\models\query.py" in _fetch_all 1186. self._result_cache = list(self._iterable_class(self)) File "C:\Python\Python36\lib\site-packages\django\db\models\query.py" in __iter__ 54. results … -
gunicorn modul not found django heroku
first time deploying to heroku. I got the test app deployed and I ran the migrations fine. However, I got the following error ModuleNotFoundError: No module named 'djorg2' I ran heroku logs --tail and got the following result here here is the a pic of my file paths and here is my current Procfile web: gunicorn djorg2.wsgi --log-file - I'm a little new to deploying on heroku. Does anyone know what my problem might be and/or count point me in the right direction. I been trying to trouble shoot this for the good part of an afternoon and I'm a little stuck. -
Create a print manager in django
I'm struggling with the following issue: I created a django app which work well. I' d like to add a print manager with a queue list of documents, then print them all in one time ! Here is my logic: I have many kind of text entries (id est many apps with entries i'd like to print....) for each text entry, i created a detailview (CBV): PrintEntry , which links to a new page with an appropriate template (using template inheritence, i extend each "kind" of entry with a specific template) Instead of clicking on "print" for each entry, i'd like to store them in a list to be able to print all entries in one time, later. Each list is obviously specific to each user. Until there, i don't have any problem. I created a Manytomany relationship between users and entries to store the url of the entry to print (url to PrintEntry). As long as i have different apps, for each app i have a PrintEntry class in my views, therefore there is different url stored. My strategy at this point is to generate a pdf file from each link stored, then merge all the pdf, and print … -
Trying to make a delete option for entries to a blog on django/heroku
I have a project (learning_log) where you can add topics and in those topics you can add entries. I have an edit entries option but I want to add a delete entries option too. I did the following, but I am still getting an internal error when I try to load it on heroku. : Made the url... urls.py urlpatterns = [ #... #Page for deleting an entry path('delete_entry/',views.delete_entry,name='delete_entry'), ] wrote the view views.py def delete_entry(request, entry_id): """Delete an existing entry""" entry = get_object_or_404(Entry,id=entry_id) #getting the entry object the user wants to delete topic=entry.topic check_project_owner() #This is a custom function (I know it works) Making sure the person who wants to delete it is the owner entry.delete() #Delete the entry context = {'entry':entry} #I don't even think we need to pass this but I just want to be safe and pass something return render(request, 'learning_logs/delete_entry.html', context) made the html template delete_entry.html {% extends "learning_logs/base.html" %} {% block content %} <a>Your quote has been deleted. Please click a link at the top of the page to return.</a> {% endblock content %} linked to it from my "edit entries page" edit_entries.html {% extends 'learning_logs/base.html' %} {% load bootstrap3 %} {% block header … -
Compress images with Pillow in Django
I have a project with Django and I use Pillow to store images in some models, but I want those images to be stored compressed. How can I instruct Pillow to compress the images when they are saved to a model ImageField? This is an example of a model with an ImageField: class Photo(models.Model): name = models.CharField(max_length=100, null=True, blank=True, verbose_name=_("Name")) album = models.ForeignKey(Album, on_delete=models.PROTECT, related_name='photos', verbose_name=_("Album")) photo = models.ImageField(verbose_name=_("Photo")) class Meta: verbose_name = _("Photo") verbose_name_plural =_("Photos") def __str__(self): return "[{}] {}".format(self.pk, self.name) I can see the file once stored, and I can see it has the same size than the original source file. I am using Django Rest Framework to get images from the front-end. -
django last tag object is not subscriptable
I apologies to ask but... I been trying on this "last" tags in my HTML with my Django framework to bring out the last object in my database to be display on my html; here doc:https://docs.djangoproject.com/en/2.1/ref/templates/builtins/ Now the problem was when I use my "last" tags on my code; <div class = "float-right my-4 chartjs-render-monitor" id="chartContainerPH" style="width: 49%; height: 400px;display: inline-block; background-color:#FDFDFD;"> <center> <a class="title-link" href="{%url 'ph' %}">PH:</a> <p> {% for tank_system in tank %}{{tank_system.PH|last}}, {%endfor%}</p> </center> </div> and get this errors; TypeError at / 'decimal.Decimal' object is not subscriptable Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.1.3 Exception Type: TypeError Exception Value: 'decimal.Decimal' object is not subscriptable Exception Location: C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\defaultfilters.py in last, line 540 Python Executable: C:\Users\user\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.1 Python Path: ['C:\\Users\\user\\Desktop\\FrounterWeb- postgreDB', 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip', 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs', 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python37-32\\lib', 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python37-32', 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages'] Server time: Thu, 6 Dec 2018 11:12:47 +0800 I'm not clear on this errors but even after read here: In Python, what does it mean if an object is subscriptable or not? here's my code on models; from django.db import models from django.utils import timezone # having errors KeyError: "'__name__' not in globals" class tank_system(models.Model): PH = models.DecimalField(max_digits=3, decimal_places=1) EC = models.DecimalField(max_digits=3, decimal_places=1) WaterLevel = models.IntegerField(default=100) TempWater = models.IntegerField(default=0) … -
How to access inner loop with value of outer loop of Django
Is it possible to access the inner loop using the key of the outer loop in the Django template as follows? {% for a in a_list %} {% for b in b_list %} # ← this is a dict <p>{{ b.a }}</p> # ← what i wan't to do! {% endfor %} {% endfor %} -
Show server errors into html
I am validating a form that I have to send via ajax, I am using axios to do this, but I'd like to now if is there someway to show the errors that I receive from server into my html, these are the errors I want to show I am using django rest-framework in the server side This is my code axios({ method: 'post', url: `${baseURL}api/users/`, contentType: 'application/json', data : {} // I send the inputs data here }) .then(response => { window.location.href = '/success.html'; console.log(response) }) .catch(err => { console.log(`It works ${err.message}`); }) Doing like this, I only can show the message like 'It works Request failed with status code 400'