Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Call a method that is set to use a specific argument, that is not available
I have a question that I do not know how to solve. I have a list view where I list user in a table with on each row some informations such as first_name last_name and a link to the user detail page. the URL for both page are in the form, list view : .../pk1/, detail view : .../pk1/pk2 where pk1 is project_id and pk2 is user_id On that detail page I make some calculation in order to get a user score and I would like to show that user score on each row in my list view. The problem is that in order to calculate that score it extracts data using pk2 which is not available on my list view since the URL contain only pk1 here is an example of one of the method used to calculate the user score: def get_applicant_team_list(self, format=None, *args, **kwargs): current_team_member = list(Project.objects.get(id = self.kwargs['pk1']).team_id.members.all()) current_applicant = MyUser.objects.get(id =self.kwargs['pk2']) current_team_member.append(current_applicant) applicant_response_list = [] for member in current_team_member: applicant_id = member.id applicant_response = get_user_response(applicant_id) applicant_response_list.append({applicant_id:applicant_response}) return applicant_response_list def get_applicant_info_array(self, format=None, *args, **kwargs): response_list = get_applicant_team_list(self) info_array = get_info_array(response_list) return info_array How can I call my methods for each user in the context of my … -
Django startup error on IIS
When I try to start my Django app on IIS I have the error such below: Error occurred while reading WSGI handler: Traceback (most recent call last): File "C:\inetpub\wwwroot\ddr\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) File "C:\inetpub\wwwroot\ddr\wfastcgi.py", line 633, in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) File "C:\inetpub\wwwroot\ddr\wfastcgi.py", line 605, in get_wsgi_handler handler = handler() File "C:\Python27\lib\site-packages\django\core\wsgi.py", line 14, in get_wsgi_application django.setup() File "C:\Python27\lib\site-packages\django__init__.py", line 17, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "C:\Python27\lib\site-packages\django\conf__init__.py", line 48, in getattr self._setup(name) File "C:\Python27\lib\site-packages\django\conf__init__.py", line 44, in setup self._wrapped = Settings(settings_module) File "C:\Python27\lib\site-packages\django\conf__init__.py", line 92, in init mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Python27\lib\importlib__init__.py", line 37, in import_module import__(name) File ".\config\settings\production.py", line 21, in SECRET_KEY = env("DJANGO_SECRET_KEY") File "C:\Python27\lib\site-packages\environ\environ.py", line 117, in call_ return self.get_value(var, cast=cast, default=default, parse_default=parse_default) File "C:\Python27\lib\site-packages\environ\environ.py", line 250, in get_value raise ImproperlyConfigured(error_msg) ImproperlyConfigured: Set the DJANGO_SECRET_KEY environment variable StdOut: StdErr: Django secret key is written in handler mappings. Maybe someone had the such error and know what I should do? Thank you all. -
How to convert this javascript code to python
I have this code in Python, actually my views.py of an app in Django project: import json from django.shortcuts import render from django.http import HttpResponse from rest_framework.views import APIView from panel.serializers import UserSerializer from panel.models import Caseworker # Create your views here. class UserAPI(APIView): serializer = UserSerializer def get(self, request, format=None): list = Caseworker.objects.all() response = self.serializer(list, many=True) return HttpResponse(json.dumps(response.data), content_type='application/json') That returns me this JSON: [{"name": "John", "last_name": "Caseworker", "telephone": "+38168999456", "email": "john@caseworker.com", "organization": "Organization 1"}] What I need to do is adapt this javascript into my python code app.get('/jokes', function(request, response) { const requestOptions = { uri: 'https://icanhazdadjoke.com/', headers: { Accept: 'application/json' }, json: true }; requestPromise(requestOptions) .then(function(data) { response.json({ messages: [ {text: data.joke} ] }); }); }); Because I have to adapt the JSON that python gives to me with this specific structure response.json({ messages: [ {text: data.joke} ] }); But actually I don't know how to do it without break my python code. -
django M2M Field issue
Django M2M problem, i am trying to get QoutID selected in the form template and then save it in the Selected Field M2M The createview is working fine with null value but in the UpdateView i would like to update SELECTED field based on selection in the form template views.py class QoutationAttachUpdateView(SuccessMessageMixin, UpdateView): template_name = "ePROC/Acquisition/qoutation_update_attach.html" model = QoutationSelection form_class = QoutationSelectForm context_object_name = 'qoutupdate' success_message = 'Record updated successfully and Requestor is notified by mail' #def dispatch(self, request, *args, **kwargs): # self.AcqID = QoutationSelection.objects.get(id=self.kwargs['pk']) # return super(QoutationAttachUpdateView, self).dispatch(request, *args, **kwargs) success_url = reverse_lazy('ePROC:ePROCHOME') def form_valid(self, form): instance = form.save(commit=False) data =QoutationSelection.objects.get(QoutID=form.instance.QoutID) instance.Selected.set(data) instance.save() return super(QoutationAttachUpdateView, self).form_valid(form) Models.py class QoutationModel(models.Model): REF=models.CharField(max_length=40,default='BKB-Q-') RequestItem=models.ForeignKey(CreateACQModel,on_delete=None,related_name='CreateRID') RequestQuantity=models.PositiveIntegerField(validators=[MinValueValidator(1)]) VendorID=models.ForeignKey(VendorModel,on_delete=None,related_name='VendorID') ccy=models.CharField(choices=ccych,max_length=40) amount=models.PositiveIntegerField(validators=[MinValueValidator(1)]) date=models.DateTimeField(auto_now_add=True) status=models.CharField(max_length=40,choices=QouteCH,default='Received') descr=models.TextField(null=True, max_length=200) qoute=models.FileField(upload_to='documents/',validators=[FileExtensionValidator(['pdf','zip','rar', 'txt', 'jpg', 'gif', 'doc', 'docx', 'xls', 'xlsx'])],blank=True, null=True) def __str__(self): return '%s' %(self.REF) class Admin: pass def get_absolute_url(self): return reverse('qoutation-list', kwargs={'pk':self.id}) class QoutationSelection(models.Model): AcqID=models.ForeignKey(CreateACQModel,on_delete=None) QoutID=models.ManyToManyField(QoutationModel) Selected=models.ManyToManyField(QoutationModel,related_name="Selected") def __unicode__(self): return '%s' %(self.REF) def __str__(self): return '%s' %(self.REF) forms.py class QoutationSelectForm(forms.ModelForm): QoutID = forms.ModelChoiceField( queryset=QoutationSelection.objects.all(), required=False,empty_label=None ) class Meta: model = QoutationSelection labels = { "Status":"Status", "AcqID":"Acquisition ID", "qoutid":"Qoutation ID", } exclude=['AcqID','Selected',] def __init__(self, *args, **kwargs): super(QoutationSelectForm, self).__init__(*args, **kwargs) if self.instance and self.instance.pk: self.fields['QoutID'].queryset = self.instance.QoutID.all() -
How to extend users from other db in django?
I am joining two Django apps and they will have "users" in common both Apps are in different databases. I was using a routers and everything was working fine but the problem appeared when I was trying to import User from the other db. My users model looks like this: class Company(models.Model): company_name = models.CharField(max_length=250, null=True) active = models.BooleanField(default=True) class Meta: verbose_name = "Company" verbose_name_plural = "Companies" def __str__(self): return self.company_name class CompanyUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) company = models.ForeignKey(Company) token = models.TextField(null=True,blank=True) class Meta: verbose_name = "Users - Company" verbose_name_plural = "Users - Company" In my view I have this: from users.models import Company, User company = request.user.username #This is fine company = request.user.companyuser.company This gives error I am getting this error **User has no companyuser** -
How to POST data from a multiple select box in Django Rest Framework
I am trying to use AJAX to make a POST request to DRF. One of my fields is a multiple select box. I can't seem to find a way to make the request work properly. I have tried posting the entire select box like below. var roles = $('#roles').val(); I have also tried posting an array of the values. var roles = $('#roles').find('option:selected').map(function(){return $(this).val()}).get(); My AJAX call looks like this: $.ajax({ method: "POST", url: "/v1.0/relationships/" + url, data: {roles: roles} ) My API view looks like this: class RelationshipSingle(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.GenericAPIView): """ /relationship/{id} Method Action GET Return details of relationship with ID {id}. POST Invalid option. PATCH Edit the relationship. DELETE Delete the relationship. """ queryset = Relationship.objects.all() serializer_class = RelationshipSerializer def get(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) def patch(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) def delete(self, request, *args, **kwargs): return self.destroy(request, *args, **kwargs) My serializer looks like this: class RelationshipSerializer(serializers.ModelSerializer): class Meta: model = Relationship fields = '__all__' -
Django raise KeyError(key) From None?
I'm trying to deploy my project into production but I'm having trouble configuring it up properly. This is the current error I got return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\1111\Desktop\2222\2222\settings.py", line 23, in <module> SECRET_KEY = os.environ['SECRET_KEY'] File "C:\Users\1111\AppData\Local\Programs\Python\Python36-32\lib\os.py", line 669, in __getitem__ raise KeyError(key) from None KeyError: 'SECRET_KEY' C:\Users\1111\Desktop\2222> line 23 of settings.py SECRET_KEY = os.environ['SECRET_KEY'] Please help , no idea what to do -
How to treat CMS fields that support HTML [Django]
I have a Django site with a Post object like so: class Post(models.Model): title = models.CharField(max_length=100,blank=True,null=True) body = models.TextField(blank=True,null=True) author = models.ForeignKey(User,blank=True,null=True) date_created = models.DateTimeField(default=timezone.now) date_updated = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to=post_dir, blank=True, null=True) def __unicode__(self): return unicode(self.date_created.strftime('%Y-%m-%d %H:%M') + ' ' + self.title) which outputs body TextField like so in order to support HTML: {% if post.body %} <p> {{ post.body | safe }} </p> {% endif %} My question is, since the admins can input HTML which could potentially malform the html (such as post.body = '</div></div>'), what is the best way to format and sanitize this textfield while still allowing users to input html? -
How to add the last_login_ip, when the user login if using `rest-auth`?
How to add the last_login_ip, when the user login if using rest-auth? Befor ask the post I searched one post bellow: How can I do my logic in `http://127.0.0.1:8000/rest-auth/login/` of `django-rest-auth`? The answer is perfect for custom verify the login params. But, how about after login, then add attribute to the User? I mean, the answer is just for verify the data, I want to after user login success, I want to add the last_login_ip to the user instance. -
Any remaining kwargs must correspond to properties or virtual fields - what does it mean?
I was trying with different model relationships, when came across this exception (please write if you want to see the full traceback): File "C:\Users\1\vat\tpgen\tpgen\src\generator\views\wizard.py", line 172, in get_next_form return step, form_type(**kwargs) File "C:\Users\1\vat\tpgen\venv\lib\site-packages\django\db\models\base.py", line 495, in __init__ raise TypeError("'%s' is an invalid keyword argument for this function" % kwarg) TypeError: 'data' is an invalid keyword argument for this function As I understand, the exception was raised when Django tried to create a new instance with some kwargs. The traceback points to Models’ __init__ method in django.db.models.base if kwargs: property_names = opts._property_names for prop in tuple(kwargs): try: # Any remaining kwargs must correspond to properties or # virtual fields. if prop in property_names or opts.get_field(prop): if kwargs[prop] is not _DEFERRED: _setattr(self, prop, kwargs[prop]) del kwargs[prop] except (AttributeError, FieldDoesNotExist): pass for kwarg in kwargs: raise TypeError("'%s' is an invalid keyword argument for this function" % kwarg) The kwargs seems to be all right (printed from the line 171 of wizard.py): {'data': None, 'prefix': '2', 'initial': {'0': {'0-trans_type': ['13'], '0-end_of_tax_year': ['']}, '1': {'1-funct_title': ['14']}}} So the problem, as I understand it, lies in the model, which I admit is a bit overcomplicated, but as said before, I was experimenting with models relationships. The … -
A worker run more than one task when I use django-celery which be control by supervisor
As I know, if I start a work with no -c and it would start "Number of child processes processing the queue. The default is the number of CPUs available on your system." like the document say. http://docs.celeryproject.org/en/latest/reference/celery.bin.worker.html#cmdoption-celery-worker-c Now I had a system ,the number of CPUS is 1. When the project run a long time,I found this: the worker_0 run five process? So many RECEIVED status. Then, the system become slowly very much. Some others say, I may should add -c to limit the number,but, the default should be 1, also would not come like this? E,en,the system is a ECS from a-li. The question: Could some one explain the reason of the phenomenon? The way to solve the problem is not necessary, of course, better if can solve it. -
What is django session? Where the session data is stored?
I am new to django session. I hope you can help me. In my django application, i just have used django session for storing user type data type1 or type2 request.session['user']='type1'. I have used default database backend for session. I have a couple of doubts. 1, Where the data is stored. If the data is stored in database, why i can't access this session from different locations? 2, Basically, a session is related to the login user only? 3,How can i access this data through direct sql queries? -
JQuery talking to DJango REST API. Need to return number of pages in response
Am new to Django REST framework. I have an application that has a listings page. When page is loaded, JQuery should talk to API and when response received it should display a list of available entertainers, which I need paginated. I have pagination working but currently have the number of page links hard coded. I need the either the total number of records or the number of pages returned in the response from the API so that I can dynamically build the links in the template I have tried it a few ways but have not been successful Firstly by passing in Response from my views.py which uses a Class based view if self.request.GET['page'] is not None: if self.request.GET['page'] != 'all': page = self.request.GET['page'] recordsPerPage = 8 paginator = Paginator(entertainers, recordsPerPage) total_records = paginator.count num_pages = paginator.num_pages entertainers = paginator.page(int(page)) return Response({ 'count': paginator.count, 'num_pages': paginator.num_pages, 'results': serialized_data }) This produced an "Internal Server Error" The other way I tried to do it was to add in a custom field in my serializers.py file but it also gave an Internal Server error class EntertainerSerializer(serializers.ModelSerializer): my_field = serializers.SerializerMethodField('record_count') def record_count(self, foo): return foo.name == "10" class Meta: model = Entertainer fields … -
Speed up model property of _set in Django
I have a relatively simple setup with a string of Parent->Child relationships. **Parent Child** Site BU BU CT CT Line Line WS WS Assess So each child has models.ForeignKey(Parent) The business logic is structured like a pyramid. Line's level (1-2-3) is dependent on all of it's childs WS level. A CT's level is dependent on all of it's line's level. BU's level on CTs level Site on BUs level. For example: WS1 \ WS2 - line 1 -- CT 1 -\ WS3 / / \ line 2 -/ \ CT 2 -- BU 1 -\ .. Site 1 .. CT 3 -- BU 2 -/ .. line 9 -- CT 4 -/ line 10 -/ Here's the issue: Each level has a property to set the color. Asking for the Site color (top of the pyramid) initiates 1266 queries on my development database with a minimum amount of dummy data. That is a huge amount. Does anyone know how to better model the color property? It is taking a 4+ seconds to get the site color on a production server with only a few sites, with the intent of adding many additional ones. model.py excerpt: class CT(models.Model): name = models.CharField(max_length=255, … -
Rendering dynamic variable in a django template
I am trying to render dynamic Url in Django template as follows <a href={{'jibambe_site_detail/'|add: site.id}}>{{ site }}</a>. This however is returning a TemplateSyntaxError at /jibambe_sites/ add requires 2 arguments, 1 provided. What am I missing or how should I render this dynamic URL, I want it to produce something like jibambe_site_detail/1 -
cloning project from github but manage.py runserver doesn't work
So I tried cloning a project that I contribute to in Github. But, when I tried to run python manage.py runserver, it showed me the following error Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\CLAIRE\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\CLAIRE\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 317, in execute settings.INSTALLED_APPS File "C:\Users\CLAIRE\Anaconda3\lib\site-packages\django\conf\__init__.py", line 56, in __getattr__ self._setup(name) File "C:\Users\CLAIRE\Anaconda3\lib\site-packages\django\conf\__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "C:\Users\CLAIRE\Anaconda3\lib\site-packages\django\conf\__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\CLAIRE\Anaconda3\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'now' Can someone please help me, please -
How to get two django rest framework to communicate with each other
So i have 2 django project. Both have its seperated database and table. I create the django rest framework api for both project but i want both of them to communicate with each other. In django 1 is about the social media and medical record app API. In django 2 is a clinic app API where the it is for staff of the clinic and collect user information from django 1 and to give a queue number for user that make appointment. What im trying to do is django 2 will have a qr code for django 1 to scan. After scanning, it will ask for permission to allow their information to be share with django 2(their user information/medical record). After user allow, their information will be save to django 2 database. For now, i just want to allow django 2 to save the user information from django 1. Is there a way for 2 different django project to communicate with each other through the api ? -
Run Background Task in Django (Threading)
I declared a class inherited threading.Thread in django which requests a url and saves an object according to and it works perfect on my computer but when i uploaded to server, Thread was just working makes a response to my main request and after that, thread destroys AddModelThread(movie_id).start() executes when i request the server and after my response the thread destroys! in my Thread i request a website(using requests class python) then i save an object -
Django admin not working?
I just setup a new server on Digital Ocean. Updated Django to 1.11, uploaded my project, ran collectstatic and I've made sure my settings match another project I have (which is live and works 100%). However, my static doesn't collect correctly into my static folder (which I have it set to do), any media I upload wont display, and the admin still has the all design from before I updated it to 1.11... Any thoughts? settings code below.. INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.flatpages', 'listings', 'stats', 'users', 'allauth', 'allauth.account', 'allauth.socialaccount', ) ... STATIC_ROOT = os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ '/static/', ] #MEDIA MEDIA_ROOT = '/home/django/django_project/media/' MEDIA_URL = '/media/' Also here's a picture of my file structure: Note that admin did not collect in static -
Updating an UserProfile in Djanngo 1.11
I'm a new developer and I was wondering if you could help me out, updating the values of my User/UserProfile through an editing form. I didn't know at the beginning but now I know I could have extended the (default) User Model and by doing that avoiding creating a new Model UserProfile for the profile purpose and making things simpler (e.g. using generic views). Since I'm still learning I have decided to try a workaround to push myself into thinking instead of appealing to a complete solution. But now I'm stuck for a few days and decided to ask you for some help. I had already looked for similar questions here and in Django's official documentation, but since I didn't follow a specific recipe, I couldn't find something to fix it properly. That's what I've got so far: models.py class UserProfile(models.Model): GENDER_CHOICES = ( ('M', 'Masculino'), ('F', 'Feminino') ) user = models.OneToOneField(User, on_delete=models.CASCADE) profile_image = models.ImageField(upload_to='uploads/', blank=True, null=True) gender = models.CharField(max_length=40, blank=True, null=True, choices=GENDER_CHOICES) birthday = models.DateField(blank=True, null=True) address = models.TextField(max_length=300, blank=True, null=True) city = models.TextField(max_length=50, blank=True, null=True) country = models.TextField(max_length=50, blank=True, null=True) def __str__(self): return str(self.id) forms.py class CustomUserForm(ModelForm): class Meta: model = User fields = [ 'username', 'id', … -
Connecting Django Dashboard with Chatfuel
I have this project where I have to connect my Django app with a Chatfuel bot. I have my admin panel, so whenever I update a field like complete certain task, I have to notify my client through the chatbot that this field change. I read JSON API docs and I noticed that they have an specific "template" to get data from a backend. What I did is extract all my data from the models through Django Rest Framework and convert it to a JSON. The thing is I don't know how to use this information to work with it in Chatfuel because my JSON hasn't the template that Chatfuel requires. This is my info extracted from the models. This is what Chatfuel needs. -
failed to use virtualenv in pycharm
enter image description here I actually have python file in scripts but I can't import python in script while importing new environment -
How to prefetch multiple fields by the same queryset
I'm trying to do a Prefetch on my Models The Models are like so: Model A ---Field 1 ---Field 2 Model B ---Field RR FK to Model A related_name RR ---Field SS FK to Model A related_name SS I was making a prefetch for my model A and I ended up with something like this B = B.objects.all() A = A.prefetch_related( Prefetch('RR', queryset=B), Prefetch('SS', queryset=B) ) However, this results in 2 queries (one for RR, and one for SS) to the same queryset. Is there any way to avoid this by making RR and SS use the same prefetch? -
Unable to create the django_migrations table (ORA-02000: missing ALWAYS keyword)
I'm starting a project in Django-2.0.1 with a database Oracle 11g, and when I run $python manage.py migrate, I get the error django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (ORA-02000: missing ALWAYS keyword). You can see the full stack below: Traceback (most recent call last): File "/Users/user/anaconda3/lib/python3.6/site-packages/django/db/backends/utils.py", line 83, in _execute return self.cursor.execute(sql) File "/Users/user/anaconda3/lib/python3.6/site-packages/django/db/backends/oracle/base.py", line 500, in execute return self.cursor.execute(query, self._param_generator(params)) cx_Oracle.DatabaseError: ORA-02000: missing ALWAYS keyword The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/user/anaconda3/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 55, in ensure_schema editor.create_model(self.Migration) File "/Users/user/anaconda3/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 298, in create_model self.execute(sql, params or None) File "/Users/user/anaconda3/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 117, in execute cursor.execute(sql, params) File "/Users/user/anaconda3/lib/python3.6/site-packages/django/db/backends/utils.py", line 100, in execute return super().execute(sql, params) File "/Users/user/anaconda3/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/Users/user/anaconda3/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File "/Users/user/anaconda3/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/Users/user/anaconda3/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/Users/user/anaconda3/lib/python3.6/site-packages/django/db/backends/utils.py", line 83, in _execute return self.cursor.execute(sql) File "/Users/user/anaconda3/lib/python3.6/site-packages/django/db/backends/oracle/base.py", line 500, in execute return self.cursor.execute(query, self._param_generator(params)) django.db.utils.DatabaseError: ORA-02000: missing ALWAYS keyword During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 15, in <module> … -
How do we write child templates that extends more than one parent template in Django?
I've been learning Django through an Udemy course and got through Template Inheritance. From what I understand it works as follows: templates/myapp/parent.html <div class="container"> {% block child_block %} {# delegated to child template #} {% endblock %} </div> templates/myapp/child.html <!DOCTYPE html> {% extends "myapp/parent.html" %} {% block child_block %} <!-- child content --> {% endblock %} We have a parent template parent.html and a child template child.html. The parent template declares a block that it will delegate to the child template. The child template declares the parent it extends and then declares the same block with the content it contains. During page construction, Django will construct the parent template, reach the block, and fill it with the content declared by the child template ---with the stipulation that you don't use blocks with the same name in any given template (to prevent name collision). This pattern works great for use-cases where a parent template may have multiple children and/or multiply nested children. You organize the template code more efficently and in smaller more manageable blocks. If a child were to be repeated N times (usually through a for loop), you delegate a block within the for loop to ensure each iteration …