Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Keycloak and Django 4 (DRF)
everyone! This is the last hope to understand how django and keycloak works together? The main problem is: I read a lot of documentation about authorization through jwt-token, I know everything what it is. So, but I can't imagine, how to integrate keycloak authorization in a django project. There are 5 or more libraries to work with keycloak. Which one I should use? I already have all configurations in a keycloak by admins, all env variables like KEYCLOAK_CLIENT_SECRET, KEYCLOAK_PUBLIC_KEY etc. What is the algorithm to work with KK in Django? I know, that I need to create 3 additional URL's to work with: First one gonna to check the credetionals to check, that user could authorize before and if not - redirect him to the second URL ↓ Second - user authorizes in KK and goes to third URL Third - I meet user on this URL and get the scope and some info here After that, I'm going to KEYCLOAK_ACCESS_TOKEN_URL, where I got the token Next - decode this token and get the roles and some data Can someone show me how it goes on practice? At this moment I should to register the user in django and do … -
Is there a way to know if related objects have been prefetched?
Is there any way to know whether related objects have been prefetched from inside a model instance? Suppose one has class Order( models.Model): ... def is_all_in_stock( self): # how to do this? class LineItem( models.Order): order = models.ForeignKey( Order, ..., related_name='line_items') stock = models.ForeignKey( Stock, ...) ... And one wants to generate some report of all orders that are delayed for assorted reasons for order in orders: # orders is a queryset ... out_of_stock = any([ line.stock.status != IN_STOCK for line in order.line_items.all() ]) This is efficient if one is iterating over a queryset that did .prefetch_related( "line_items", "line_items__stock). It doesn't hit the DB at all. It hammers the DB if not. On the other hand, using a queryset like out_of_stock = order.line_items.exclude( stock__status = IN_STOCK ).exists() hits the DB only once for each order, the classic N+1 problem Is it possible to write the method order.is_all_in_stock(self) to take advantage of what has been prefetched if it has been prefetched, and to fall back on running a query each time it is called if not? -
Django and Django rest framework + email
How could i achieve email functionality using drf as backeend and django to hit these apis.What i need how will user be confirm from django while using drf to send activation link. -
How to get(access) foreign key's member instance in django?
articles/models.py class Article(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) user/models.py class User(AbstractUser): username = models.CharField(max_length=20) email = models.EmailField(_('email address'), unique=True) profile_image_url = models.TextField() Is there any other way to include or access user's member instance (username, email, profile_image_url) into class Article?? I'd like to make class Article into this class Article(models.Model): User.username User.email User.profile_image_url FYI,my Serializer are these class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = ['emotion', 'location', 'menu', 'weather', 'song', 'point', 'content', 'image', 'user', 'created', 'liked', 'num_liked'] class UsersSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'date_joined', 'email', 'profile_image_url', 'followings', 'followers') Is there any other way to make my ArticleSerializer to include UserSerializer's fields? or Is there any other way to include or access user's member instance (username, email, profile_image_url) into class Article?? -
Django: Leaflet map does not render when adding new item in admin inline
I am using the django-leaflet package to display the maps in the admin. I have a model that I am inserting as TabularInline, where one of the fields is a PointField. model.py class Occurrence(models.Model): name = models.CharField(max_length=254) location = models.PointField(null=True, blank=True) # ....... admin.py class OccurrencesInline(LeafletGeoAdminMixin): model = Occurrence fields = ('name', 'location') show_change_link = True extra = 1 formset = AtLeastOneFormSet The map appears correctly in the extra rows that appear initially. However, when I add a new item, instead of the map, a text box appears. Any idea why this is happening and how to fix it? -
How to fix Django's Internal Server Error on their latest release?
I am setting up the base html page that I will use to extend for the rest of my project. I am finished setting it up (The same way I always do, besides a few minor html and wording changes) but I keep getting ValueError at / dictionary update sequence element #0 has length 1; 2 is required Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.0.3 Exception Type: ValueError Exception Value: dictionary update sequence element #0 has length 1; 2 is required Exception Location: /home/blackhood/.virtualenvs/djangoenv/lib/python3.9/site-packages/django/urls/resolvers.py, line 421, in resolve Python Executable: /home/blackhood/.virtualenvs/djangoenv/bin/python3 Python Version: 3.9.7 Python Path: ['/home/blackhood/Apps/sobriety_app', '/usr/lib/python39.zip', '/usr/lib/python3.9', '/usr/lib/python3.9/lib-dynload', '/home/blackhood/.virtualenvs/djangoenv/lib/python3.9/site-packages'] Server time: Fri, 20 May 2022 08:14:33 -0500 It seems like there is an issue inside Django's code base, but I know it's more likely that I am making an error somewhere. I will post the HTML code first and then the code for each script in the landing app. __landing/templates/landing/base.html__ <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <!-- Font Awesome Link --> <script src="https://kit.fontawesome.com/216d1cce07.js" crossorigin="anonymous"></script> <title>App Title</title> </head> <body> {% include 'landing/navbar.html' %} {% block content %} {% … -
No UID when using Django admin page to create objects
So I have created a custom User model and a common model as base for all other models that adds a created_by field. If I now use the Django admin page to create an object(just for testing) then I get the error that the UID is Null. class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): """Creates and saves a new User""" if not email: raise ValueError("Users must have an email address") user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): """creates and saves a new superuser""" user = self.create_user(email, password) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class CommonModel(models.Model): """Common fields that are shared among other models""" created_by = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.PROTECT, editable=False, related_name="+", ) So it seems like when using the admin page to create objects the UID cannot be resolved. Any ideas? -
Django user.authenticate always returns None
Models.py class User(AbstractBaseUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(_('email address'), unique=True) password = models.CharField(max_length=50) phone_number = models.CharField(max_length=100) last_login = models.DateTimeField(auto_now=True) is_confirmed = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email Managers.py class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) Settings.py AUTH_USER_MODEL = 'users.User' My django app is named as 'users'. So basically I'm trying to implement my own users using the AbstractBaseUser and I want authentication using email & password, tried everything still unable to get the … -
Javascript : QuerySelector fail and can not add an inner tag
My goal is to display a pdf from a blob Url. I want to add a tag to the html code <iframe src='${blobUrl}' type="application/pdf"></iframe> to diplay the pdf file. Here is the full code : html {% load static %} <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> {{ encodedstring | json_script:'mydata' }} <div class="pdfdisplay"></div> <script> function b64toBlob(b64Data, contentType, sliceSize) { contentType = contentType || ''; sliceSize = sliceSize || 512; var byteCharacters = atob(b64Data); var byteArrays = []; for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) { var slice = byteCharacters.slice(offset, offset + sliceSize); var byteNumbers = new Array(slice.length); for (var i = 0; i < slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i); } var byteArray = new Uint8Array(byteNumbers); byteArrays.push(byteArray); } var blob = new Blob(byteArrays, {type: contentType}); return blob; } var contentType = 'application/pdf'; var b64Data = JSON.parse(document.getElementById('mydata').textContent); var blob = b64toBlob(b64Data, contentType); var blobUrl = URL.createObjectURL(blob); const target = document.querySelector('div.pdfdisplay'); target.innerHTML = <iframe src='${blobUrl}' type="application/pdf"></iframe>; </script> </body> </html> When I inspect the page generated, nothing is added to <div class="pdfdisplay"></div> and the page is blank. I know that the error comes from ther queryselector but I do not see what … -
NoReverseMatch at /accounts/confirm-email/
when i try to create account ( signup ) it show this error ( i am using django alluth ) django.urls.exceptions.NoReverseMatch: Reverse for 'contact' not found. 'contact' is not a valid view function or pattern name. In template /home/qq/Desktop/earnapp/templates/account/base.html, error at line 15 urls.py : path( "confirm-email/", views.email_verification_sent, name="account_email_verification_sent", ), re_path( r"^confirm-email/(?P<key>[-:\w]+)/$", views.confirm_email, name="account_confirm_email", ), base.html : <!DOCTYPE html> {% load static %} <html dir="rtl"> <head> <title>{% block head_title %}{% endblock %}</title> {% block css %} {% endblock css %} {% block extra_head %} <!-- booststrap link js + ajax + css --> <script src="{% static "js/jquery.min.js" %}"></script> <script src="{% static "js/bootstrap.min.js" %}"></script> <script src="{% static "js/site.js" %}"></script> <link rel="stylesheet" href="{% static "css/bootstrap.min.css" %}"> <link rel="stylesheet" href="{% static "css/site.css" %}"> <meta name="viewport" content="height=device-height, initial-scale=.82, maximum-scale=2, user-scalable=no"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script type="text/javascript"> error in line 15 is <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> -
cannot iterate through payload to get the desired output
I'm trying to the iterate through the payload where there is a Qstan I want it to get in the desired output like 12|Yes&&13|Yes&&14|Yes&&15|Yes&&16|Yes&&17|Yes&&18|Yes&&19|Yes&&. I have tried to get in separate like 12|Yes&& 13|Yes&&. All I wanted is to concatenate QId and Answer before it saves to the database. How could I achieve this browser payload 0: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "Yes", QId: 150…} 1: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "No", QId: 151…} 2: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "Yes", QId: 152…} 3: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "Yes", QId: 153…} 4: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "No", QId: 154…} 5: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "Yes", QId: 155…} 6: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "No", QId: 156…} Here, what I tried @api_view(['POST']) def SaveUserResponse(request): if request.method == 'POST': data = [] cursor = connection.cursor() for ran in request.data: auditorid =ran.get('AuditorId') print('SaveUserResponse auditorid---', auditorid) ticketid = ran.get('TicketId') qid = ran.get('QId') answer = ran.get('Answer') sid = ran.get('SID') print('sid--', sid) TicketType = ran.get('TicketType') TypeSelected = ran.get('TypeSelected') agents = ran.get('Agents') supervisor = ran.get('Supervisor') Comments = ran.get('Comments') action = ran.get('Action') subfunction = … -
How to get azure subscriptionid from subscription name using python
I am trying to create a azure resource id in python script using information of provider and resourcegroup name. which will be used for rest api calls. But the problem is I have only name of subscription. How can I fetch subscriptionId in my prog? -
Is there a way to improve the health of EB environment?
I tried to create a new application with a new environment in AWS Elastic Beanstalk and the it ran ok to begin with. But once I uploaded and deployed (successfully) my Django app on it, it degraded in health to severe. The error is : Environment health has transitioned from Degraded to Severe. 100.0 % of the requests are failing with HTTP 5xx. My application runs fine on my machine. I have set up the requirements and remove pywin32 and pypiwin32 from it coz this is a linux instance on AWS. Also here is my django.config file in .ebextensions: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: employee_records.wsgi:application I have added all changes (including the virtual env) to staging area in github. I have chosen the application load balancing (default 2). So please help as to why this error occurs. -
Creating custom fields with django-filters
I have a model as shown below. The model has the attribute type as a foreign key. class YachtGeneralInfo(models.Model): type = models.ForeignKey( YachtTypes, related_name="yachts_in_type", on_delete=models.PROTECT, blank=False, null=False, ) .... .... I wrote a view class like this - class YachtGeneralInfoView(ListAPIView): pagination_class = PageNumberPagination serializer_class = YachtGeneralInfoSerializer filter_backends = [OrderingFilter, SearchFilter, DjangoFilterBackend] filterset_fields = [ "status", "is_professional", "chartered_with__id", "harbour__id", "harbour__city__id", "model__id", ] search_fields = ["name", "company_name", "website", "owner__name"] I would like to add another filter for field type. However, I want to provide multiple values for this query parameter like [1,2,3]. If I do that directly with queryset then it would be like this - queryset = YachtGeneralInfo.objects.filter(type__in=[1,2,3]) Is there a way I could write a custom filter set field to accomplish this instead of having it directly in the queryset? -
Django model field setting to NoneType after objects.create
Im using objects.create to create object o my model. Using the following logic. But payment_quantity (somehow) is setting to NoneType. And not setting to the value i passed into objects.create class PrizesExchangeModeResourceBMR(resources.ModelResource): @transaction.atomic def create_exchange_mode(self, code, points, price): cuotas = [1,3,6,12] # array de cuotas prize = Prize.objects.filter(code = code) # busca el premio if len(prize) != 0: # si existe el premio PrizesExchangeMode.objects.create( #crea puntos al 100%, 0 cuotas prize = prize[0], payment_amount = 0, points_value = points, payment_quantity=0, price_value = 0 ) puntos = round(points/2) for cuota in cuotas: # crea con puntos al 50% y [1,3,6,12] cuotas valor = round(price/cuota) PrizesExchangeMode.objects.create( prize = prize[0], payment_amount = valor, points_value = puntos, payment_quantity = 0.0, price_value = 0.0) else: print("Premio no encontrado") # no existe el premio def get_instance(self,instance_loader, row): self.get_queryset().get(prize__code=row.get('prize')) def save_instance(self, instance, using_transactions, dry_run): code = instance.prize.code #guarda el codigo points = instance.points_value # guarda puntos price = instance.payment_amount # guarda precio self.create_exchange_mode(code, points, price) # se lo pasa a la funcion anterior class Meta: model = PrizesExchangeMode fields = ("prize", "points_value", "payment_amount") # Campos que queremos importar -
Is there a way too attach another django db in a SQL query?
Like the title says, is there a way to use the following SQL code with the ATTACH: attach "..\directory...\database1.sqlite3" as input; select columnx, columny from (select column1, column2 from input.sites) I am selecting column x and y from database2 and i want to attach database1 so that I can query it in the select statement while also querying database2. I have both database1 and 2 in my settings.py file with routers and models which all works great. At the moment I am bypassing the ORM (Sqlite) and using SQL query like so which works great: database='C:/... database1.sqlite3' db=sqlite3.connect(database) c=db.cursor() sql_command='SELECT * FROM customers' customer = c.execute(sql_command) customer = c.fetchall() I could'nt find anything int he django docs about ATTACH so any advice is appreciated! -
No module named 'django_redis' even imported
I have the error ".InvalidCacheBackendError: Could not find backend 'django_redis.cache.RedisCache': No module named 'django_redis'" Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\cache\__init__.py", line 39, in create_connection backend_cls = import_string(backend) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\module_loading.py", line 17, in import_string module = import_module(module_path) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django_redis' File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\cache\__init__.py", line 43, in create_connection ) from e django.core.cache.backends.base.InvalidCacheBackendError: Could not find backend 'django_redis.cache.RedisCache': No module named 'django_redis' I installed django_redis I ping my redis_cli in my setting.py, I add the code CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", 'TIMEOUT': 60 * 60 * 8, "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", }, "KEY_PREFIX": "lkd" } } But the error still appear that no module named django_redis Please help me to solve my issue -
AttributeError: module 'lib' has no attribute 'X509_get_notBefore'
WARNINGS: ?: (2_0.W001) Your URL pattern '^complete/(?P<backend>[^/]+)/$' [name='complete'] has a route that contains '(?P<', begins with a '^', or ends with a '$'. This was likely an oversight when migrating to django.urls.path(). ?: (2_0.W001) Your URL pattern '^disconnect/(?P<backend>[^/]+)/$' [name='disconnect'] has a route that contains '(?P<', begins with a '^', or ends with a '$'. This was likely an oversight when migrating to django.urls.path(). ?: (2_0.W001) Your URL pattern '^disconnect/(?P<backend>[^/]+)/(? P<association_id>\d+)/$' [name='disconnect_individual'] has a route that contains '(?P<', begins with a '^', or ends with a '$'. This was likely an oversight when migrating to django.urls.path(). ?: (2_0.W001) Your URL pattern '^login/(?P[^/]+)/$' [name='begin'] has a route that contains '(?P<', begins with a '^', or ends with a '$'. This was likely an oversight when migrating to django.urls.path(). Traceback (most recent call last): File "manage.py", line 22, in main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Hp\anaconda3\lib\site-packages\django\core\management_init_.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Hp\anaconda3\lib\site-packages\django\core\management_init_.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Hp\anaconda3\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Hp\anaconda3\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Users\Hp\anaconda3\lib\site-packages\django_extensions\management\utils.py", line 62, in inner ret = func(self, *args, **kwargs) File "C:\Users\Hp\anaconda3\lib\site-packages\django_extensions\management\commands\runserver_plus.py", line 262, in handle self.inner_run(options) File "C:\Users\Hp\anaconda3\lib\site-packages\django_extensions\management\commands\runserver_plus.py", line 339, in inner_run … -
Djangochannelsrestframework websocket firstly connects and disconnect
I'm working on a project which uses WebSockets,I'm trying to create websocket connection with djangochannelsrestframework. I tried all like in documentation and I got an error after I start my code by daphne. Everything works fine but when I start a project with daphne turned on the socket keeps connecting and disconnecting with a gap of split second. Any ideas? -
How to pass a variable in a function to update many to many field
I have several functions like: def update_m2m(): ... ... book.author.add(*authors_ids) ... I have the same piece of code for updating other many to many fields. How can I make a separate function for it. For example def update_m2m(obj, field_name, ids): ... ... setattr(obj, field_name, ids) ... But setattr doesn't work for m2m field. Is there any other solution for this? -
Django: Save with related fields via forms
I am fairly new to Python and Django so please bare with me. I have two classes which are related via a ForeignKey. I am trying to save both of them via one screen, create.html which links to view.py. I then specify the models used in form.py. My setup is below and I get the print of Not Valid. I'm not sure what I am doing wrong. model.py class Request(models.Model): title = models.CharField(max_length=50, null=True) description = models.CharField(max_length=200, null=True) class RequestDocument(models.Model): request = models.ForeignKey(Request, related_name='documents', on_delete=models.CASCADE) document = models.FileField(upload_to=request_document_upload_handler) view.py def requests_create_view(request): obj = Request form = RequestForm(request.POST or None) formset = RequestDocumentForm(request.POST or None) context = { "form": form, "formset": formset, "object": obj } if all([form.is_valid(), formset.is_valid()]): parent = form.save(commit=False) parent.save() child = formset.save(commit=False) child.request = parent child.save() context['message'] = 'Data saved.' context['created'] = True else: print('Not Valid') return render(request, "requests/create.html", context) forms.py class RequestDocumentForm(forms.ModelForm): document = forms.FileField() class Meta: model = RequestDocument fields = ['document'] class RequestForm(forms.ModelForm): class Meta: model = Request fields = ['title', 'description'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # django-crispy-forms for field in self.fields: new_data = { "class": 'form-control', } self.fields[str(field)].widget.attrs.update( new_data ) self.fields['description'].widget.attrs.update({'rows': '10'}) create.html {% if not created %} <div style="margin:80px"> <h1>New Request</h1> … -
How to create chart from a dict?
I have a dict like: print(assigned_incidents) => [ {'name': 'Eda', 'case_type': 'Med'}, {'name': 'Deniz', 'case_type': 'High'}, {'name': 'Alex', 'case_type': 'Med'} {'name': 'Eda', 'case_type': 'High'} ] I want to display it in a chart.js chart as a stacked bar chart. For example 'eda' has 2 Med and 1 High case: var assignedIncidents = new Chart(document.getElementById('assigned_incidents').getContext('2d'), { type: 'bar', data: { labels: assigned_incidents-->name, datasets:assigned_incidents-->case_type }' options: { plugins: { }, scales: { x: { stacked: true, }, y: { stacked: true } }, responsive: true } }); How can I do that? -
How to add list field in the django restframework sqlite
how to add list field in the sqlite db in django restframework camera = models.ForeignKey(Camera, on_delete=models.CASCADE) updated_time = models.DateTimeField(auto_now_add=True) objects_inself = models.???? -
How to assign a user to a model in my database
from django.db import models from datetime import datetime from django.contrib.auth import get_user_model User = get_user_model() class Blog(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) headline = models.CharField(max_length=250) content = models.CharField(max_length=2050) time_created = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.user.username every time I migrate this "(venv) PS C:\Users\user\Desktop\APPS\web_app_project> python manage.py makemigrations" I always get this message: "It is impossible to add a non-nullable field 'user' to blog without specifying a default. This is because the database needs something to populate existing rows. Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) Quit and manually define a default value in models.py. Select an option:" How do I go about this -
Django form submit not working without refreshing the whole page
I want to submit the values of the form to views.py. I have tried doing it through jQuery but it's not working. I can see that the page is not refreshing after hitting the submit button because of the e.preventDefault(); but the values are not getting fetched at all. Please let me know where I am going wrong. index.html <form method="POST" action="" id="form"> {% csrf_token %} <div class="d-flex justify-content-center" style="margin-top: 6rem"> <div class="dropdown" style="display: flex" id="dropdown"> <select class="form-select" aria-label="Default select example" name="options_value" id="dropdown_val" > <option disabled hidden selected>---Select---</option> <option value="1">Profile UID</option> <option value="2">Employee ID</option> <option value="3">Email ID</option> <option value="4">LAN ID</option> </select> </div> <div class="col-3 bg-light" style="margin-left: 2rem"> <input type="text" class="form-control" id="in3" type="text" placeholder="Enter Value" name="value" id="value" /> </div> <div style="margin-left: 2rem"> <input class="btn btn-primary" type="submit" value="Submit" style="background-color: #3a0ca3" /> </div> </div> </form> <script> let form = document.getElementById("form"); let dropdown_val = document.getElementById("dropdown_val"); let val = document.getElementById("value"); const csrf = document.getElementsByName("csrfmiddlewaretoken")[0].value; form.addEventListener("submit", (e) => { e.preventDefault(); const newform = new FormData(); newform.append("dropdown_val", dropdown_val.value); newform.append("val", val.value); newform.append("csrfmiddlewaretoken", csrf); fetch("{% url 'home' %}", { method: "POST", body: newform, }); }); </script> views.py def home(request): if request.method=="POST": options_value=request.POST['dropdown_val'] value=request.POST['val'] print(options_value,value)