Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
jQuery Datatables rendered with django ordering not working
I can't seem to get this table to order on click. The app is retrieving a table from Django and rendering it successfully. But when I go ahead and click the arrows at the top of the table columns, a box says 'processing' but no reordering happens. When I disable serverSide programmatically so that it should only happen the first time, the ajax call happens anyway. $(document).ready( function () { $.fn.dataTable.ext.errMode = 'throw'; var table = $('#{{ grid_id }}').DataTable({ "paging": {{paging}} ,"searching": false ,"info": true ,"stateSave": false ,"orderable": true ,"ordering": true ,"processing": true ,"serverSide": true {% if ajax_url is not None %} ,"ajax": { /* "type": "POST", */ "url": "{{ ajax_url }}", "dataSrc": "results", "data": function (d) { d.customParam = "custom"; } }{% endif %}{% if column_list is not None %} ,"columns": [ {% for col in column_list %} { "title":"{{ col.title }}", "data": "{{ col.data }}" {% if col.href is not None %}, fnCreatedCell: function (nTd, sData, oData, iRow, iCol) { $(nTd).html("<a href='{{col.href}}"+oData.{{ col.href_data_attr }}+"'>"+oData.{{ col.data }}+"</a>");}{% endif %} },{% endfor %} ] {% endif %} }); }); -
DJANGO. form not working, button action is null
I am working on the checkout for an ecommerce site and everything is set but the form to choose the shipping and billing addresses before filling the credit card info. I have no clue why the form is not working, its not passing any data nor performing any action. The 3 data fields that I am passing are saved to an existing order model which already contains info like price, products, etc. The order model works perfectly fine as well as everything else in the site. This is the form in my template: <form method="POST" name="check_address"> {% csrf_token %} <div> <h4 class="mb-3">Dirección de envío</h4> {% if shipping_addresses %} <div class="list-group form-group mb-2"> {% for address in shipping_addresses %} <a class="list-group-item list-group-item-action flex-column align-items-start"> <div class="d-flex w-100 justify-content-between"> {% if request.user.defaultaddresses.shipping.id == address.id %} <input type='radio' name="shipping_address" form="check_address" value="{{address.id}}" checked> {% else %} <input type='radio' name="shipping_address" form="check_address" value="{{address.id}}"> {% endif %} <h5 class="mb-1">Dirección</h5> </div> <p class="mb-1">{{address.street_address}}{% if address.apartment_address %} {{address.apartment_address}}{% endif %}</p> <small class="text-muted">{{address.get_city}}</small> </a> {% endfor %} </div> <div id="collapseTwo" class="collapse mt-3 mb-3"> <h5 class="mb-3">Nueva dirección de envío</h5> {% include 'snippets/addressform.html' %} </div> {% else %} {% if address_form %} {% include 'snippets/addressform.html' %} {% endif %} {% endif %} … -
I am using celery beat in django to schedule periodic tasks. Django ==2.0
File "/home/yash/Documents/erp_notify/env/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/yash/Documents/erp_notify/env/lib/python3.6/site-packages/django/db/models/query.py", line 417, in create obj.save(force_insert=True, using=self.db) File "/home/yash/Documents/erp_notify/env/lib/python3.6/site-packages/django_celery_beat/models.py", line 567, in save super(PeriodicTask, self).save(*args, **kwargs) File "/home/yash/Documents/erp_notify/env/lib/python3.6/site-packages/django/db/models/base.py", line 729, in save force_update=force_update, update_fields=update_fields) File "/home/yash/Documents/erp_notify/env/lib/python3.6/site-packages/django/db/models/base.py", line 769, in save_base update_fields=update_fields, raw=raw, using=using, File "/home/yash/Documents/erp_notify/env/lib/python3.6/site-packages/django/dispatch/dispatcher.py", line 178, in send for receiver in self._live_receivers(sender) File "/home/yash/Documents/erp_notify/env/lib/python3.6/site-packages/django/dispatch/dispatcher.py", line 178, in for receiver in self._live_receivers(sender) File "/home/yash/Desktop/er/erp_back/erp/erp/middleware/middleware.py", line 132, in create_user_profile if not 'LogRecord' in str(instance): File "/home/yash/Documents/erp_notify/env/lib/python3.6/site-packages/django_celery_beat/models.py", line 581, in str if self.interval: File "/home/yash/Documents/erp_notify/env/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 158, in get rel_obj = self.field.get_cached_value(instance) File "/home/yash/Documents/erp_notify/env/lib/python3.6/site-packages/django/db/models/fields/mixins.py", line 13, in get_cached_value return instance._state.fields_cache[cache_name] AttributeError: 'PeriodicTask' object has no attribute '_state' -
Django channels username sender
i new to django channels , i followed the documentation tutorial and i made a django chat room , so far i can send and recieve messages , but the probleme here the sender is unknown , i tryied to send the username but its not working , i get the username printed in the server but in the front i get the actual login username?? i am confused ? consumer.py : class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name self.user = self.scope["user"] # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group async def chat_message(self, event): message = event['message'] print(self.user.username) # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message, 'username' : str(self.user.username), })) room.html : <!-- chat/templates/chat/room.html --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Chat Room</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <div style="width:800px; margin:0 auto;">username : <a id="username" href="">{{ user.get_username }}</a> <textarea id="chat-log" cols="100" … -
How to add @property auto calculation part in django to mysql
In django I created some auto calculation parts using @property function. While I was connected to dbsqlite3 it showed the calculated amounts. But when I change the database to mysql database it is not adding the calculation part in database. class leave(models.Model): leave_id = models.CharField(max_length=20, primary_key=True, default="") emp_det_id = models.ForeignKey( 'emp_details', models.DO_NOTHING, default="") l = ( ("Paid", "Paid"), ("Non-Paid", "Non-Paid") ) leave_type = models.CharField(max_length=50, choices=l, default="Non-Paid") m = ( ("January", "January"), ("February", "February"), ("March", "March"), ("April", "April"), ("May", "May"), ("June", "June"), ("July", "July"), ("August", "August"), ("September", "September"), ("October", "October"), ("November", "November"), ("December", "December") ) month = models.CharField(max_length=10, choices=m, default="January") year = models.CharField(max_length=4, default=2021) s = ( ("Accepted", "Accepted"), ("Pending", "Pending"), ("Canceled", "Canceled") ) status = models.CharField(max_length=10, choices=s, default="Pending") def __str__(self): return self.leave_id class salary(models.Model): sal_id = models.CharField(max_length=10, primary_key=True, default="") emp_det_id = models.ForeignKey('emp_details', models.DO_NOTHING, default="") dept_id = models.ForeignKey('department', models.DO_NOTHING, default="") basic_sal = models.IntegerField(default=0) extra_hours = models.IntegerField(default=0) bonus = models.IntegerField(default=0) @property def Extra_Payment(self): return self.extra_hours * 350 @property def get_leave_count(self): leaves = salary.objects.filter(emp_det_id=self.emp_det_id, emp_det_id__leave__month=self.month, emp_det_id__leave__year=self.year, emp_det_id__leave__status='Accepted').aggregate(leave_count=Count('emp_det_id__leave')) return leaves['leave_count'] @property def leave_amount(self): return self.get_leave_count * 500 @property def Total_Payment(self): return self.Extra_Payment + self.basic_sal + self.bonus - self.leave_amount m = ( ("January", "January"), ("February", "February"), ("March", "March"), ("April", "April"), ("May", "May"), ("June", "June"), ("July", … -
Django ORM. Joining subquery on condition
I have a table TickerStatement, which contains financial statements about companies class Statements(models.TextChoices): """ Supported statements """ capital_lease_obligations = 'capital_lease_obligations' net_income = 'net_income' price = 'price' total_assets = 'total_assets' short_term_debt = 'short_term_debt' total_long_term_debt = 'total_long_term_debt' total_revenue = 'total_revenue' total_shareholder_equity = 'total_shareholder_equity' class TickerStatement(TimeStampMixin): """ Model that represents ticker financial statements """ name = models.CharField(choices=Statements.choices, max_length=50) fiscal_date_ending = models.DateField() value = models.DecimalField(max_digits=MAX_DIGITS, decimal_places=DECIMAL_PLACES) ticker = models.ForeignKey(Ticker, on_delete=models.CASCADE, null=False, related_name='ticker_statements') And now I'm trying to calculate a multiplier. The formula looks like: (short_term_debt + total_long_term_debt) / total_shareholder_equity I wrote a raw SQL query SELECT "fin_tickerstatement"."fiscal_date_ending", t2.equity AS "equity", value AS "debt", short_term_debt AS "short_term_debt", (value + short_term_debt) / t2.equity AS "result" FROM "fin_tickerstatement" JOIN (SELECT "fin_tickerstatement"."fiscal_date_ending", fin_tickerstatement.value AS "equity" FROM "fin_tickerstatement" WHERE ("fin_tickerstatement"."ticker_id" = 12 AND "fin_tickerstatement"."fiscal_date_ending" >= date'2015-09-03' AND "fin_tickerstatement"."name" = 'total_shareholder_equity') GROUP BY "fin_tickerstatement"."fiscal_date_ending", fin_tickerstatement.value ORDER BY "fin_tickerstatement"."fiscal_date_ending" DESC) t2 ON fin_tickerstatement.fiscal_date_ending = t2.fiscal_date_ending JOIN (SELECT "fin_tickerstatement"."fiscal_date_ending", fin_tickerstatement.value AS "short_term_debt" FROM "fin_tickerstatement" WHERE ("fin_tickerstatement"."ticker_id" = 12 AND "fin_tickerstatement"."fiscal_date_ending" >= date'2015-09-03' AND "fin_tickerstatement"."name" = 'short_term_debt') GROUP BY "fin_tickerstatement"."fiscal_date_ending", fin_tickerstatement.value ORDER BY "fin_tickerstatement"."fiscal_date_ending" DESC) t3 ON fin_tickerstatement.fiscal_date_ending = t3.fiscal_date_ending WHERE ("fin_tickerstatement"."ticker_id" = 12 AND "fin_tickerstatement"."fiscal_date_ending" >= date'2015-09-03' AND "fin_tickerstatement"."name" = 'total_long_term_debt') GROUP BY "fin_tickerstatement"."fiscal_date_ending", equity, debt, short_term_debt ORDER BY "fin_tickerstatement"."fiscal_date_ending" DESC; and … -
Is it possible to let a user choose how many fields to be filled?
I am planning to do an application with Django where the user shall inform how many columns and which data types will be submitted through a CSV file. I know I can define, in the views.py, formats, create MultiValueFields, and have the CSV content into a JSONField in the database. But the ideal would have to have individual tables for each informed CSV, in the database, because I will need to access specific parts of that data many times and I fear eventually extracting a lot of JSON dictionaries and processing the whole data chunck to pick parts of it will not scale well. As for what I know, a Model you write on models.py, is a role model for Django to create specific columns on the database table, through makemigrations and migrate commands. As it is a pretty static and reliable way on functioning, it really is bugging me if it is not possible to dynamically allocate data. I have already thought on two ways of doing it, while still using Django: To create a model with a lot of ModelFields, each of them not being required to be filled and NULL as default value; The JSONField solution. But … -
querying my objects from db using profile id
` class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) full_name = models.CharField(max_length=200, null=False) image = models.ImageField(default='default.jpg', upload_to='profile_pics') date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) class Course(models.Model): title = models.CharField(max_length=200, null=False) description = models.CharField(max_length=200, null=False) tutor = models.ForeignKey(Tutor, on_delete=models.CASCADE) students = models.ManyToManyField(Student) def __str__(self): return self.title def Courses(request): current_user = request.user print(current_user.id) courses = Course.objects.filter(students__id=current_user.id) return render(request, 'e-learning/courses.html', {'courses':courses}) `I have a model student that is related to a model course via many to many relationship. i want to query all the courses related to the current logged in user, who is a student. -
Heroku Connection increase unreasonably
I am new to Heroku. I am currently using the free tier which has limited to 20 connection. I deployed a wsgi (postgres) and redis app (Django back-end) to Heroku. I am facing a weird issue where there is only one user using it but the connection keep increasing and even the app is killed, the connection is still there. May i know what is the root cause of this problem? The connection increases even the chat is not perform but just using simple API. -
Problem with textarea "query_utils.DeferredAttribute" message in empty form
I am new in Django and i am making a typical CRUD app. In the "add" section, in the comment textarea this message appears "<django.db.models.query_utils.DeferredAttribute object at 0x03B446A0>" and i dont know what to do. I had tried multiples solutions in other stackoverflow questions but i cant find the solutions, i hope you can help me! Here's the code class Turno(models.Model): date = models.DateTimeField() person = models.ForeignKey('Person', on_delete=models.CASCADE) medic = models.ForeignKey('Medic', on_delete=models.CASCADE) observations = models.CharField(blank=True, max_length=255) def __str__(self): return f'{self.date} {self.person} {self.medic}' def new_turn(request): if request.method == 'POST': turnFormPost = TurnForm(request.POST) if turnFormPost.is_valid(): turnFormPost.save() return redirect("admin_index") turnForm = TurnForm(instance=Turno) context = { 'form':turnForm } return render(request,"turn_new.html", context) class TurnForm(ModelForm): class Meta: model = Turno fields = '__all__' widgets = { 'date': DateTimeInput(attrs={'type':'date'}), 'observations': Textarea(attrs={'rows':5, 'cols':50}) } -turn_new.html <div class="container"> <h2>New Turn</h2> <form method="POST"> {% csrf_token %} <table> {{form}} </table> <button type="submit" class="btn btn-primary">Create</button> </form> <div> <a href="{% url 'new_turn' %}">Back to index</a> </div> </div> in the textarea of 'observations' in 'turn_new.html' the message that appears is this "<django.db.models.query_utils.DeferredAttribute object at 0x03B446A0>" -
Django - Postgres Full Text Search customization word segmentation
I'm trying to implement full-text search functionality for my website. We decided to go for PostgreSQL full-text search on first iterations because of it's simplicity to setup. I found out that Postgres doesn't have good support for our website users' language. Thus the word segmentation came with Postgres will not work. I want to use the tsquery generated by our own parser instead of letting the Postgres function do that for me. Please tell me if there's a way to do it by Django builtin ORM. This is the way Postgres does a full-text search without gin index. SELECT title FROM pgweb WHERE to_tsvector('english', body) @@ to_tsquery('english', 'friend'); If Django ORM cannot achieve the desired functionality, then is it possible to search instead like this by using a custom query and custom parser hosted in my backend? SELECT title FROM pgweb WHERE my_own_parsed_tsvector @@ my_own_parsed_tsquery; Further I'd like to know if building a GIN index with custom parsers are possible. I'd really appreciate it for any possible help. -
Django: Validating POST data from a manually built form
I've built a page that shows a list of all available products (Item) and allows user to add a product to their order, as well as adjust the quantity. My three models: Order Item OrderItem where Item is a model to create products for sale. OrderItem is created once an Item is added to an Order. class Order(models.Model): user = models.ForeignKey(...) class Item(models.Model): title = models.CharField() description = models.TextField() class OrderItem(models.Model): item = models.ForeignKey(Item) quantity = models.IntegerField() order = models.ForeignKey(Order, related_name='items') The page that lists all of the products is essentially a ListView on Item. However, I've annotated the Item.object to include order_item quantity (if it exists): views.py: order_item = request.order.items.filter(item=OuterRef('pk')) items = Item.objects.all().annotate(order_quantity=Subquery(order_item.values('quantity'))) context = { 'items': items } return render(self.request, 'services.html', context) In services.html, I loop through items, and display the title and description, as well as build a form with input box for quantity: <form method="post"> {% for item in items %} {{ item.title }} {{ item.description }} <span onclick="document.querySelector('#item-{{ item.pk }}-quantity').stepDown()" class="minus">—</span> <input style="text-align: center; width: 3rem" class="quantity" min="0" name="{{ item.pk }}" value="{% if item.order_quantity %}{{ item.order_quantity }}{% else %}0{% endif %}" type="number" id="item-{{ item.pk }}-quantity"> <span onclick="document.querySelector('#item-{{ item.pk }}-quantity').stepUp()" class="plus">+</span> </form> Now, in my view, … -
how run celery worker as a part of django management command?
I am totally new with celery + django, so here is the question: I know that according to celery documentation to make it running, we need to create a celery.py file, and then start a worker as an independent process like that: celery -A proj worker -l info I wonder if there is an option to run it through a custom management command instead of running it this way. The reason for this is that I use a third-party django-based platform (oTree), which modifies settings.py before starting, which means that I can't do in celery.py the way they recommend: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') So if somehow I would manage to start celery from within django (like a custom management command), the environment this process would run in, would already get modified settings, which would work. Any ideas how to do that? -
Iterating through dictionary items from Django html template
I'm new to Django and like to learn the basics first. I was looking for an answer about iterating dictionary from a template. There are couple of questions similar to mine but no one mention the way that is the simplest and works. However, as I don't have enough reputation I can't comment. Therefor, I created this one here as I really want it to be seen. Example: let's say we create our dictionary in the def inside views.py as below: def home_page(request): person = {"name": "Saif", "Phone": 111111111} context = {"person": person.items} return render(request, 'home.html', context) Then in home.html for example, we can iterate easily: {% block body %} {% for key, value in person %} <p>{{ key }}:{{ value }}</p> {% endfor %} {% endblock %} I tried other answers but all didn't work and this one works for me. Thanks, -
Proper auth testing structure in Django
I'm implementing Django REST Framework Social OAuth2 and I'm wondering what my test class / unit tests should look like if I want to imitate 3 out of the 5 testing steps done in the "Testing the Setup" section at: https://github.com/RealmTeam/django-rest-framework-social-oauth2#testing-the-setup I'm basing the structure of my test class on this example: https://docs.djangoproject.com/en/3.1/topics/testing/tools/#example My test.py: import unittest from django.test import Client class SimpleTest(unittest.TestCase): def setUp(self): # Every test needs a client. self.client = Client() self.client_id = <my_client_id> self.client_secret = <my_client_secret> self.user_name = <my_user_name> self.password = <my_password> def test_drf_social_oauth2_setup(self): '''Following testing steps found at https://github.com/RealmTeam/django-rest-framework-social-oauth2#testing-the-setup''' # Retrieve token for user # curl -X POST -d "client_id=<client_id>&client_secret=<client_secret>&grant_type=password&username=<user_name>&password=<password>" http://localhost:8000/auth/token response = self.client.post( '/auth/token', { 'client_id': self.client_id, 'client_secret': self.client_secret, 'grant_type': 'password', 'username': self.user_name, 'password': self.password } ) # Check that the response is 200 OK self.assertEqual(response.status_code, 200) # Check that the response contains an access token self.assertEqual('access_token' in response.json(), True) ;print(f'Token retrieval returned: {response.json()=}') # Refresh token # curl -X POST -d "grant_type=refresh_token&client_id=<client_id>&client_secret=<client_secret>&refresh_token=<your_refresh_token>" http://localhost:8000/auth/token response = self.client.post( '/auth/token', { 'grant_type': 'refresh_token', 'client_id': self.client_id, 'client_secret': self.client_secret, 'refresh_token': response.json()['refresh_token'] # Use refresh token from previous test } ) # Check that the response is 200 OK self.assertEqual(response.status_code, 200) # Check that the response contains a new … -
How to send dictionary context data to view from template in django
I am passing a dict object to template and using that dict object to fill up table data. But depending on the need I want to send that dictionary data to another view for processing. I tried sending data using URL parameter which is affecting data in dictionary. View class GeneratedReportView(View): """ View to display all details about a single patient @param: is_single_document: bool, if true it means only single document exist for patient and to display only one col in html page """ model = Patient template_name = 'patient/patient_generated_report.html' context_object_name = 'object' form = GeneratedReportForm() # helper function def create_final_report(self, doc1_obj: Document, doc2_obj: Document = None, is_single_document: bool = False) : # template of how data is passed on to html page table = { 'doc1_name':'', 'doc2_name':'', 'label':{ 'doc1': {'value':'value', 'unit':'unit'}, 'doc2': {'value':'value', 'unit':'unit'}, 'remark': '', #`doc1_value - doc2_value`, 'remark_color': '', #`red or green`, } } # # some code to populate table data # return table, is_single_document def get(self, request, pk): # instantiating form for selected particular user form = GeneratedReportForm(pk=pk) patient_obj = Patient.objects.get(pk=pk) # retrieving all document of patient.pk = pk from latest to oldest documents = Document.objects.filter(patient__id=pk).order_by('-uploaded_at') table, is_single_document = None, None doc1_obj, doc2_obj = None, … -
Django Rest Framework: How to ignore 'unique' primary key constraint when validating a serializer?
I am attempting to store large amounts of transit data in a PostgreSQL database, where a client uploads multiple records at a time (in the tens of thousands). I only want one arrival time per stop, per route, per trip and the unique identifier for that stop, route, and trip is the primary key for my table (and a foreign key in a different table). I am trying use Django's update_or_create in my serializer to either create the entry for that arrival time or update the arrival time with the latest data if it already exists. Unfortunately, while calling is_valid() on my serializer, it identifies that the repeat records violate the uniqueness constraint of the primary keys (which makes sense), giving me this error message: 'real_id': [ErrorDetail(string='actual with this real id already exists.', code='unique')] I want to override this behavior since if the primary key isn't unique it will just update the entry. I have already tried looping over and removing validators like so: def run_validators(self, value): for validator in self.validators: self.validators.remove(validator) super(ActualSerializer, self).run_validators(value) I have also tried removing all validators using the extra_kwargs field of my serializer Meta class like so: extra_kwargs = { 'name': {'validators': []} } I … -
Error occured when migrate mysql in django
I installed mysql client -- pip install mysqlclient but when i made connection to mysql using this code 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'django_db', 'USER' : 'root', 'PASSWORD' : '', 'HOST' : '127.0.0.1', 'PORT' : '8080' } following error returns : django.db.utils.OperationalError: (2013, "Lost connection to MySQL server at 'reading initial communication packet', system error: 0") -
Templates not found after refactoring settings.py for django-dotenv usage
I want to use django-dotenv to manage my enviroment variables. Before I had 3 files: base.py, dev.py, prod.py. Now I have 1 file: settings.py, that contains everything. However, my templates are not rendering anymore. Why? Every app has a template folder, where the templates are saved. settings.py: import dotenv import sys import os from decouple import config dotenv.read_dotenv() BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = os.getenv('SECRET_KEY') DEBUG = os.getenv('DEBUG') from dj_database_url import parse as dburl default_dburl = 'sqlite:///' + os.path.join(BASE_DIR, 'db.sqlite3') DATABASES = { 'default': config('DATABASE_URL', default=default_dburl, cast=dburl), } # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # Application definition INSTALLED_APPS = [ 'home', 'search', 'flex', 'streams', 'menus', 'site_settings', 'subscribers', 'blog', 'doctrina', 'storages', 'registration', 'wagtail.contrib.forms', 'wagtail.contrib.redirects', 'wagtail.contrib.settings', 'wagtail.contrib.modeladmin', 'wagtail.embeds', 'wagtail.sites', 'wagtail.users', 'wagtail.snippets', 'wagtail.documents', 'wagtail.images', 'wagtail.search', 'wagtail.admin', 'wagtail.core', 'modelcluster', 'taggit', 'django_extensions', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'debug_toolbar', 'crispy_forms' ] SITE_ID = 1 #django-allauth setting MIDDLEWARE = [ 'debug_toolbar.middleware.DebugToolbarMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'wagtail.contrib.redirects.middleware.RedirectMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), ## AQUI ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'wagtail.contrib.settings.context_processors.settings', ], }, }, ] AUTHENTICATION_BACKENDS = [ # Needed to login by username … -
password-generator project(identation problem)
hope you are well. I'menter image description here working in this password generator project. And everything was working just fine, till I started adding functions in my views.py document. The error that is showed in the command prompt is an indentation error "unindent does not match any outer indentation level". I attach a screen capture of the issue. Thanks in advance, if someone can help me out!! -
how to fix django instance of a model
Error message AttributeError: 'NoneType' object has no attribute 'add' am trying to create an instance of a model. the card model is suppose to be an instance of the patient model and the patient model has a foreign key relations with the user model. Its like a patient who has a card in the hospital. My error is coming from the perform_create method views.py class PatientCardListAPIView(ListCreateAPIView): serializer_class = PatientsCardSerializer queryset = Card.objects.all() permission_classes = (permissions.IsAuthenticated, IsOwner, ) def perform_create(self, serializer): serializer.save() serializer.instance.owner.add(self.request.user) models.py from django.db import models from authentication.models import User # Create your models here. class Patient(models.Model): name = models.CharField(max_length=255, null=True) country = models.CharField(max_length=255, null=True) state = models.CharField(max_length=255, null=True) phone = models.CharField(max_length=255, null=True) email = models.CharField(max_length=255, null=True) owner = models.ForeignKey(to=User, null=True, on_delete=models.CASCADE) def __str__(self): return self.name class Card(models.Model): name = models.CharField(max_length=255, null=True) card_number = models.CharField(max_length=255, null=True) owner = models.OneToOneField(Patient, null=True, blank=True, on_delete=models.CASCADE) def __str__(self): return self.name -
combine multiple swagger docs ( from different applications ) into one swagger dashboard [drf_yasg]
If I have 5 applications(django),with respective swagger docs, is it possible to combine all the swagger docs as one swagger docs. I'm using django rest framework. -
Django- Admin Section Improper View
I am Using Django 3 and I'm facing a weird issue in admin section. The Home page of Admin section looks proper: Admin Home But when I click on one of the tabs, the page has a random navigation bar which does not gets closed. It blocks all of the view of the page. Messed up View I haven't altered the CSS of Admin section or anything. Still I'm getting this error. How can this be solved? I can't work on admin section properly because of this. -
Django Template not rendering mission information
I'm trying to render some information in the template but it isn't showing on even though I think I implemented it right. I'm working on my consultant dashboard (consultant is a user type) My template : <div class="form-group"> {% csrf_token %} <label>Mission </label> <select class="form-control" name="mission" id="mission"> {% for mission in mission %} <option value="{{ mission.id }}">{{ mission.mission_name }}</option> {% endfor %} </select> </div> models.py: class Mission(models.Model): id=models.AutoField(primary_key=True) mission_name=models.CharField(max_length=255) client_id=models.ForeignKey(Client,on_delete=models.CASCADE,default=1) consultant_id=models.ForeignKey(Consultant,on_delete=models.CASCADE) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now_add=True) objects=models.Manager() My view: def staff_take_attendance(request): mission=Mission.objects.filter(consultant_id=request.user.id) return render(request,"staff_template/staff_take_attendance.html",{"mission":mission}) -
Django celery unable to set custom scheduler as DatabaseScheduler
I have a Django project setup and working. Celery is also working i am able to start worker as well as celery beat. Trying to use django_celery_beat and set custom scheduler class as django_celery_beat.schedulers:DatabaseScheduler in the settings file. But its still using the default PersistentScheduler. settings.py # Other settings # Celery CELERY_BROKER_URL = 'redis://localhost:6379/0' CELERY_CELERYBEAT_SCHEDULER = "django_celery_beat.schedulers:DatabaseScheduler" CELERY_RESULT_BACKEND = 'django-db' celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.schedules import crontab # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') app = Celery('myproject') app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() # my tasks imported here However when i set custom scheduler in command line like this celery -A proj beat -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler then everything works as expected. In nutshell, i want to set celery's custom scheduler in the django settings.py so that i don't need to specify that everything in the command line. UPDATE: If i change broker_url in the settings, the changes as reflected well. So there's nothing wrong with configuring settings.