Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Apply filter for EACH element in Array-Field possible?
Hello Django community! I would like to filter my database using a contained_by operation on each element in a Array/JSONB field. Example: Instance has arrayfield: [[A, B],[C, D, E]] I would like to apply following filter to find this instance (written like python in-line loop): .filter(array_element contained by [A, B, C, D, E] for array_element in array) Because the arrayfield can have variable length I cannot index each contains operation explicitly. Is there a way in Django to do something like this? Thank you for you help! -
Its possible detect if the user use pwa in django backend
in javascript it is possible to check something like: (window.matchMedia('(display-mode: standalone)').matches) || (window.navigator.standalone) || document.referrer.includes('android-app://') will return true if using pwa/twa, but I need to check the Django backend for security reasons -
group articles by day in django
I'm trying to group articles in each day, image blow will show you how it looks like now I have 3 records that have their date on top right of them, but as you can see each one of them is separated, I want to show record on this date in one group and tomorrow if I added more records shows on that date group, my codes: Models.py: class Form(models.Model): food_type = models.ForeignKey(FoodTypes, blank=False, null=True, on_delete=CASCADE) calorie = models.CharField(max_length=50) protein = models.ForeignKey(Protein, blank=False, null=True, on_delete=CASCADE) carbohydrate = models.ForeignKey(Carbohydrate, blank=False, null=True, on_delete=CASCADE) drinks = models.ForeignKey(Drinks, blank=False, null=True, on_delete=CASCADE) fruits = models.CharField(max_length=50) note = models.CharField(max_length=200, blank=True) date = models.DateField(default=datetime.date.today) views.py: def requests(request): lists = Form.objects.all().order_by('-date') context = { 'lists': lists } return render(request, 'form/requests_list.html', context) template file: {% for lists in lists %} <div class="req-list"> <h6>{{ lists.date }}</h6> <table class="table table-striped"> <thead> <tr> <th scope="col">#</th> <th scope="col">نوع غذا</th> <th scope="col">کالری</th> <th scope="col">پروتئین</th> <th scope="col">کربوهیدرات</th> <th scope="col">نوشیدنی</th> <th scope="col">میوه</th> <th scope="col">توضیحات</th> </tr> </thead> <tbody> <tr> <th scope="row">{{ lists.id }}</th> <td>{{ lists.food_type }}</td> <td>{{ lists.calorie }}</td> <td>@{{ lists.protein }}</td> <td>@{{ lists.carbohydrate }}</td> <td>@{{ lists.drinks }}</td> <td>@{{ lists.fruits }}</td> <td>@{{ lists.note }}</td> </tr> </tbody> </table> </div> {% endfor %} -
TypeError at /admin/app/doctor/add/ __str__ returned non-string (type NoneType)
In my django project my models.py: class myCustomUser(AbstractUser): username = models.CharField(max_length=20, unique="True", blank=False) password = models.CharField(max_length=200) isPatient = models.BooleanField(default=False) isDoctor = models.BooleanField(default=False) firstName = models.CharField(max_length=200, blank=True, null=True) lastName = models.CharField(max_length=200, blank=True, null=True) email = models.EmailField(unique=True) dateOfBirth = models.CharField(max_length=200, blank=True, null=True) address = models.CharField(max_length=200, blank=True, null=True) contactNo = models.IntegerField(null=True, unique=True) def __str__(self): return self.firstName class Doctor(models.Model): user = models.OneToOneField(myCustomUser, null=True, blank=True, on_delete=models.CASCADE, related_name='doctor_releted_user') degree = models.CharField(max_length=200, blank=True, null=True) speciality = models.CharField(max_length=200, blank=True, null=True) isApproved = models.BooleanField(default=False) def __str__(self): return self.user.firstName class Patient(models.Model): user = models.OneToOneField(myCustomUser, null=True, blank=True, on_delete=models.CASCADE, related_name='patient_releted_user') gender = models.CharField(max_length=200, blank=True, null=True) class Appointment(models.Model): pname = models.ForeignKey(Patient, on_delete=models.CASCADE, related_name='patient_releted_appointment', null=True, blank=True) doctor = models.ForeignKey(Doctor, null=True, blank=True, on_delete=models.CASCADE, related_name='doctor_releted_appornment') date = models.DateTimeField(null=True, blank=True) isConfiremed = models.BooleanField(default=False) After 1st migration when I trying to add any doctor object from admin pannel it says error like: TypeError at /admin/app/doctor/add/ __str__ returned non-string (type NoneType) Please suggest how can I fix it? -
Django rest framework use kwargs in serializer
I have a model Ingredient which has ForeignKey field. I use modelSerializer to pass data. I'm passing recipe_id in url like this recipes/{recipe.id}/ingredients. My current solution is to modify request.data in the view but I'm sure if it's corrent way for such a common case. What's the best way to pass Recipe to serializer? models.py class Ingredient(TimeStamp): name = models.CharField(max_length=50) quantity = models.PositiveSmallIntegerField() recipe = models.ForeignKey( Recipe, on_delete=models.CASCADE, related_name='ingredients', ) serializers.py class IngredientSerializer(serializers.ModelSerializer): class Meta: model = Ingredient fields = [ 'id', 'name', 'quantity', 'unit', 'recipe' ] views.py class IngredientViewSet(viewsets.ModelViewSet): serializer_class = IngredientSerializer def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) request.data['recipe'] = self.kwargs['pk'] serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) -
Problem when trying to import a template from a django directory
I have a django module called botmodules, for example, and I want to import a model from a django module into it. Look how I proceeded Traceback (most recent call last): File "/code/botmodules/bot.py", line 1, in <module> from events import general File "/code/botmodules/events/general.py", line 2, in <module> from ...botlogic.models import Server ImportError: attempted relative import beyond top-level package -
flutter urls.dart template file
i was following Building a Mobile App with Django & Flutter tutorial but in the tutorial they dont share the urls.dart file so my project giving errors because there is no code for urls so my project giving errors. is there a template for it? or how can i create a file from zero? in comments of the video it seems thats the only problem and huge one. thx -
Cannot get POST data from Django request.POST
I'm trying to verify that the required data was included in a POST request. I have a django backend and a vue3 frontend. Here is my django view: views.py # Sign user in and issue token @require_http_methods(['POST']) def login(request: HttpRequest): if request.method == 'POST': # check that required fields were send with POST print(request.body) if {'username', 'password'} >= set(request.POST): # <- evaluates as False print('missing required fields. INCLUDED: ' + str(request.POST)) return JsonResponse( data={'message': 'Please provide all required fields.'}, content_type='application/json', status=400) # check that username exists and password matches if (User.objects.filter(username=request.POST['username']).count() > 0): user = User.objects.get(username=request.POST['username']) if user.password == request.POST['password']: # Delete previously issued tokens Token.objects.filter(user_id=user.id).delete() token = Token(user_id=user.id) token.save() return JsonResponse(data={'userToken': token.to_json()}, content_type='application/json', status=200) else: return JsonResponse( data={'message': 'Incorrect username or password.'}, content_type='application/json', status=400) else: return HttpResponseNotAllowed(permitted_methods=['POST']) And my axios request Login.vue axios .post('http://localhost:8000/api/users/login', { 'username': form.get('username'), 'password': form.get('password'), }, { validateStatus: (status) => { return status !== 500 }, }) .then((response) => { console.log(response.data) if (response.data.success) { // Commit token value to store store.commit('setToken', response.data.token) // Request user data ... } else { alert.message = response.data.message alert.type = 'error' document.querySelector('#alert')?.scrollIntoView() } }) I can see that username and password are set in request.body but not request.POST as shown … -
custom filtering not working in django rest framework
i have tried to use custom filtering by defining a filter class and importing in my view but it is not working. My code: class ProductAPIView(ListAPIView): permission_classes = [AllowAny] serializer_class = ProductSerializer queryset = Product.objects.all() filter_backends = [DjangoFilterBackend] filterset_class = ProductFilter pagination_class = CustomPagination My filter: class ProductFilter(filters.FilterSet): variants__price = filters.RangeFilter() class Meta: model = Product fields = ['brand__name','variants__price','availability','slug','category__name', 'services','featured','best_seller','top_rated'] My models: class Brand(models.Model): name = models.CharField(max_length=100, unique=True) featured = models.BooleanField(default=False) class Product(models.Model): merchant = models.ForeignKey(Seller,on_delete=models.CASCADE,blank=True,null=True) category = models.ManyToManyField(Category, blank=False) sub_category = models.ForeignKey(Subcategory, on_delete=models.CASCADE,blank=True,null=True) mini_category = models.ForeignKey(Minicategory, on_delete=models.SET_NULL, blank=True, null=True) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) collection = models.ForeignKey(Collection, on_delete=models.CASCADE) featured = models.BooleanField(default=False) # is product featured? Now when I call localhost/api/products?brand___name__in=lg,sony it doenst filter and shows all the objects from the database. It only works when I dont put in like this localhost/api/products?brand___name=lg .But I need to query through multiple parameters. What is the issue here?? From the docs, it says i can multiple query using __in. -
Django DeleteView showing blank page when i click on delete button
I make a view with Django DeleteView CBV and when i click on delete button in delete page nothing happen and Django says: Method Not Allowed (POST): /post/delete_post/3 Method Not Allowed: /post/delete_post/3 Here is my code: views.py class DeletePostView(DetailView): model = Posts template_name = 'blog/delete_post.html' success_url = reverse_lazy('blog:all_posts') urls.py path('post/delete_post/<int:pk>', views.DeletePostView.as_view(), name='delete_post') my button: <p><a href="{% url 'blog:delete_post' object.id %}">delete post!</a></p> delete_post.html {% extends 'base.html' %} {% block title %}Delete post{% endblock %} {% block content %} <form action="" method="post"> {% csrf_token %} <p>Are you sure?</p> <input type="submit" value="Delete!"> <a href="{% url 'blog:post_detail' object.id %}">Cancel</a> </form> {% endblock %} -
How to get Django custom form validator to work?
I'm working on a custom valdator for my Django forms. Inexplicably, I can't get the result I want. Here is my code from django import forms from django.core import validators from django.core.exceptions import ValidationError from .models import Vote from django.core.validators import MaxValueValidator, MinValueValidator def use_one(value): if value != 1: raise forms.ValidationError("Value is not 1!") class MyForm(forms.Form): main_form = forms.IntegerField(validators = [use_one], label= 'Main', required = False, widget = forms.NumberInput( attrs={'id': 'mainInput', 'name': 'main, 'href': '#', 'value': '', 'class': "form-control"})) Any thoughts? views.py form = MyForm() main_result = request.GET.get(main_form) form.fields['main_form_result'].initial = main_result context = {form: form} -
Blank page on react production build with django and nginx on proxy server
I'm trying to deploy a django application on a proxy server (otlart.com, IP 111.22.333.44) and make it accessible from http://dome.com:8080/annotator. The django admin page and rest_framework render correctly, however the react build shows a blank page despite not throwing any error on page and script loading. All pages render correctly when I access 111.22.333.44:80 directly. Settings on dome.com for proxy: <VirtualHost *:8080> ServerName dome.com ServerAlias www.dome.com ServerAdmin scandav@example.com ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined ProxyRequests Off <Proxy *> Order deny,allow Allow from all </Proxy> ProxyPass /annotator http://111.22.333.44 ProxyPassReverse /annotator http://111.22.333.44 <Location /> Order allow,deny Allow from all </Location> </VirtualHost> The application folder tree is: 📦app ┣ 📂backend ┃ ┣ 📂static ┃ ┃ ┣ 📂admin ┃ ┃ ┣ 📂css ┃ ┃ ┣ 📂js ┃ ┃ ┣ 📂media ┃ ┃ ┗ 📂rest_framework ┃ ┣ 📜__init__.py ┃ ┣ 📜....py ┃ ┣ 📜settings.py ┃ ┣ 📜urls.py ┃ ┗ 📜wsgi.py ┣ 📂frontend ┃ ┣ 📂build ┃ ┃ ┣ 📂static ┃ ┃ ┣ 📜asset-manifest.json ┃ ┃ ┣ 📜index.html ┃ ┃ ┗ 📜robots.txt ┣ 📂web_annotator ┃ ┣ 📂migrations ┃ ┣ 📜admin.py ┃ ┣ 📜apps.py ┃ ┣ 📜models.py ┃ ┗ 📜views.py ┗ 📜manage.py Django settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR / "frontend" / "build", ], … -
How to upload picture using Ajax in Django ? Python
I am trying to upload profile picture using Ajax (using FormData) in Django. Following is the code I used it in html page, <img src="/media/{{user_profile.picture}}" width="150" height="150" alt="" id="pro_file"/> <input id="upload-file" type="file" name="file"/> and in jQuery (Ajax), var fd = new FormData(); var vidFileLength = $('#upload-file')[0].files.length; if(vidFileLength === 0){ var files = $('#pro_file').attr('src'); } else{ var files = $('#upload-file')[0].files[0]; } fd.append('file',files); Then I have sent the fd in data attribute in Ajax. However, in views.py following is my snippet code, fd = request.FILES try: profile_pic = fd['file'] except KeyError as e: profile_pic = request.POST['file'] profile_pic = str(profile_pic).replace("/media/","") Using this method, my code works but I doubt is it a proper way to do it ? Any suggestions please ? -
Using Client side camera, with Django, in FER
I am trying to make an emotion recognition app with Django and OpenCV. My app is also up on Azure, and I was informed that I need to access the client side camera, because there are no cameras where the Azure servers are located. I have tried to use channels to do this, but I can't seem to find a way to get the video to work the way I want to. Has anyone discovered a way to use OpenCV on the client side using Django/Channels? Here is my code so we can all look at what I have so far. camera.py import cv2 import mediapipe as mp from fer import FER import os import numpy as np from keras.models import model_from_json from keras.preprocessing import image json_file = open("emotion/fer.json") loaded_model_json = json_file.read() json_file.close() loaded_model = model_from_json(loaded_model_json) # Model setup loaded_model.load_weights('emotion/models/fer/fer.h5') detector = FER() # Media pipe face mesh mp_draw = mp.solutions.drawing_utils mp_face_mesh = mp.solutions.face_mesh faceMesh = mp_face_mesh.FaceMesh(max_num_faces=2) draw_specs = mp_draw.DrawingSpec((255, 0, 0), 1, 1) # OpenCV Haarcascade face_cascade = cv2.CascadeClassifier( 'emotion/haarcascade_frontalface_default.xml') class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture(0) self.prediction = "" self.score = 0 def __del__(self): self.video.release() def getScore(self): return self.score def getEmotion(self): return self.prediction def get_frame(self): success, frame = … -
Why can't my Django app find my function in views?
I'm new to Django and am trying to create a simple "Hello World" webpage. I've set up a project and an application, but in the urls.py of my application it says that the function I've defined in views can't be found. Pycharm seems to not even recognize the two lines of my function because it says "expected 2 blank lines, found 1" although that may not be what that means. Any ideas are appreciated. views.py main/urls.py -
Django: Urls Optional Query Parameters
Urls.py: app_name = 'main' urlpatterns = [ path('',include(router.urls)), path('player_id=<str:player>%season_id=<str:season>',views.MatchesList.as_view()) ] Views.py class MatchesList(generics.ListAPIView): serializer_class = MatchesSerializer permissions = (IsAuthenticated) def get_queryset(self): player = self.kwargs['player'] season = self.kwargs['season'] if season is None: queryset = Matches.objects.filter(player=player).all() else: queryset = Matches.objects.filter(player=player,season=season).all() return queryset Is there any way to request without the parameter 'season'? Something like that: app_name = 'main' urlpatterns = [ path('',include(router.urls)), path('player_id=<str:player>',views.MatchesList.as_view()) ] -
How to Use URL dispatcher to get clickable link to list contents of my page DJANGO
I want to make a list of items showing on my index.html page to be clickable, I used the url dynamic reverse technique but i keep getting this error. Please guide me on what I may be doing wrong. Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/%7B%25%20url%20'entrypage'%20entry%20%25 Using the URLconf defined in wiki.urls, Django tried these URL patterns, in this order: admin/ [name='index'] wiki/<str:title> [name='entrypage'] The current path, {% url 'entrypage' entry %, didn’t match any of these. URLS.PY app_name = "encyclopedia" urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:title>", views.entry_page, name='entrypage'), ] HTML <ul> {% for entry in entries %} <li> <a href="{% url 'entrypage' entry %">{{ entry }}</a> </li> {% endfor %} </ul> VIEWS.PY def entry_page(request, title): title = util.get_entry(title) if title: content = markdown2.markdown(title) context = { "title": title, "content": content, } return render(request, "encyclopedia/entrypage.html", context) else: return render(request, "encyclopedia/errorpage.html") What am i doing wrong please. I'm a beginner -
"This field is required." - in django
my model class User(models.Model): lang = models.CharField(max_length=40,choices=LANGUAGE_CHOICES, default='ru') email = models.EmailField(("E-mail"), max_length=254, unique= True) user_name = models.CharField(("Имя"),max_length=60) phone_number = models.CharField(("Телефон"),max_length=60, unique= True) date_of_meeting = models.CharField(max_length=50,choices = DATE_OF_MEETING,default = FIRST) def __str__(self): return "%s %s" % (self.user_name, self.email) my views.py I used modelform_factory() in my views to create form without forms.py. class UserView(APIView): def post(self,request,*args, **kwargs): if request.method == 'POST': form = modelform_factory(User, fields="__all__") response = form(request.POST) if response.is_valid(): response.save() return JsonResponse(status=status.HTTP_201_CREATED) else: return JsonResponse(response.errors, status=status.HTTP_400_BAD_REQUEST) my post request from postman { "lang": "ru", "email": "asdms@mail.m", "user_name": "asdasd", "phone_number": "123123", "date_of_meeting": "20-11-2021" } After post request I got: { "lang": [ "This field is required." ], "email": [ "This field is required." ], "user_name": [ "This field is required." ], "phone_number": [ "This field is required." ], "date_of_meeting": [ "This field is required." ] } How to handle that post request correctly and also write in my model? Is this error because of I didn't use serializer? -
control webpage remotely? ( telegram/discord bot )
I have a simple flask web app with a multi-step form like 3 steps for submitting information and I receive the data in a telegram bot My Question here is it possible to control the form? like if someone submits data he can pass step1 and step2 but he can't pass to step3 until I allow him by sending a command or request or something similar? and maybe display a loading or timing bar while waiting -
issue with setting up the username field in form initial in Django
I have a form with a username field. The form is available only for logged-in users. I am trying to populate the username in the User field but with no success. What am I doing wrong? models.py class Feedback(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) email = models.EmailField(default='') title = CharField(max_length=300, blank=True, null=True, default='') body = RichTextField(max_length=1500) published = models.DateTimeField(default=timezone.now) def save(self, *args, **kwargs): self.user = self.user.username super(Feedback, self).save(*args, **kwargs) forms.py class FeedbackForm(forms.ModelForm): captcha = ReCaptchaField() user = forms.CharField(initial='username') # it displays username as a string but request.user.username doesn't work here class Meta: model = Feedback fields = ['user', 'email', 'title', 'body', 'captcha'] views.py @login_required def hal_feedback(request): if request.method == 'POST': form = FeedbackForm(request.POST, initial={"username": request.user.username}) # putting request.user.username in initial also it also doesn't work if form.is_valid(): obj = form.save(commit=False) email = form.cleaned_data['email'] title = form.cleaned_data['title'] body = form.cleaned_data['body'] current_site = get_current_site(request) subject = 'Feedback' message = render_to_string('articles/post_question_confirmation.html', { 'obj': obj, 'domain': current_site.domain, 'content': body, 'title': title, }) obj.save() send_mail(subject, message, "auth.ADMIN", [email], fail_silently=False) return redirect('success') else: initial = {'username':request.user.username} form = HALFeedbackForm(initial=initial) return render(request, "articles/question.html", {'form': form}) -
Complex join of two tables - columns are grouped values from second table
So, i'm trying to make somekind of a pivot (?) table for my django project, but with no luck - details: First table - 'keyword': | id | name | fk_project_id | | -------- | -------------- |-------------------| | 1 | stack | 1 | | 2 | overflow | 1 | Second table - 'position': | id | fk_keyword_id | rank |date_created| region | | -------- | ----------------|--------|------------|--------| | 1 | 1 | 22 |2021-01-01 | UK | | 2 | 1 | 44 |2021-01-02 | UK | | 3 | 1 | 55 |2021-01-02 | FR | | 4 | 2 | 11 |2021-01-01 | FR | | 4 | 2 | 22 |2021-01-02 | FR | I want to combine that tables to one, where first column is keyword.name, and all others would create dynamically based on values 'date_created' and 'region' from second table, to have something like this: | keyword_name| UK,2021-01-01 | UK,2021-01-02|FR,2021-01-01|FR,2021-01-02| | ----------- | ----------------|----------------|-------------|-------------| | stack | 22 | 44 | 55 | null | | overflow | null | null | 11 | 22 | I am using django with postgresql, so i can get all needed names for columns before making query … -
Django to postgres, OperationalError could not load plpgsql.dll even though it is there
I have an Angular frontend/Django backend webapp where the database is hosted on a remote Windows 2019 server in postgreSQL 13. The frontend code etc. is all fine, but I'm suddenly unable to do POST and PUT requests, bet GET requests work perfectly fine. It's the same thing connecting to the database via Data Studio, SELECT statements work, but not INSERT or UPDATE. When I try, I'm getting an error with not able to load the plpgsql.dll library since the resource cannot be found, but following the filepath it's clearly there. I decided to try to open pgAdmin4, but am getting a "Fatal Error: The application server cannot be contacted" I figure this must be the root of the issue. I believe there was an update recently that may have caused this, but I'm not sure and am not very familiar with postgres or pgAdmin. I've seen some solutions to similar problems like deleting everything in the "sessions" folder, specifically regarding the fatal error, but how will this effect the data that is currently there, and would this even solve the issue of the plpgsql.dll library? Thanks -
Delete 2 model different objects which reference each other as foreign keys
We have two Django models: class Project(models.Model): project_title = models.CharField(max_length=30) owner = models.ForeignKey(User, null=True, on_delete=models.DO_NOTHING) class User(models.Model): usernmae = models.CharField(max_length=50) active_project = models.ForeignKey(User, null=True, on_delete=models.DO_NOTHING, related_name='current_project') I have a user with object (with id say 692). And this user created a project with id=12345, therefore these owner field will get have this particular referenced. I want to delete that user. But it shows error that delete on table "app_user" violates foreign key constraint This is expected as on_delete=models.DO_NOTHING, was set. One way I found out was using on_delete=models.CASCADE. Question: How should I go about deleting the user (692) without changing the model definition(having to re-run migration)? Doing it manually by deleting the project first, leads to the same foreign-key error, as owner field is User object. How to handle this mutual foreign key relationship while deleting, as deleting any one of those two throws the foreign-key exception? -
Send selected radio button id from Datatable to Django URL
I'm looking for a solution to get the value from my radio button and send it to my django url. When I get selected radio button in the first page of DataTables, it's working properly, However when select radio button from other page (not first page), I can't get the radio button value HTML <a href="{% url 'update_maintenance_issue' %}" id="edit"> <img src="{% static 'images/icons/edit3.png' %}"> </a> <table id="mytable1"> <thead align="center"> <tr align="center" style="font-weight:bold"> <th style="cursor:pointer" align="center">No</th> <th style="cursor:pointer" align="center">ID</th> <th style="cursor:pointer" align="center">Type</th> <th style="cursor:pointer" align="center">Line</th> <th style="cursor:pointer" align="center">Sequence</th> <th style="cursor:pointer" align="center">Module</th> <th style="cursor:pointer" align="center">Item</th> <th style="cursor:pointer" align="center">Sympton</th> <th style="cursor:pointer" align="center">status</th> <th style="cursor:pointer" align="center">Register</th> <th style="cursor:pointer" align="center">Assigned</th> <th style="cursor:pointer" align="center">Register dt</th> </tr> </thead> <tbody> {% for list in issue_list %} <tr> <td> <input name="radio_id" type="radio" id="radio_id" value="{{list.id}}"> </td> <td align="center">{{ list.id }} </td> <td align="center">{{ list.line_nm }} </td> <td align="center">{{ list.line_nm }} </td> <td align="center">{{ list.sequence}} </td> <td align="center">{{ list.division }} </td> <td align="center">{{ list.module }} </td> <td align="left">{{ list.sympton }}</td> <td align="left">{{ list.status }}</td> <td align="center">{{ list.register }}</td> <td align="center">{{ list.assigned }}</td> <td align="center">{{ list.register_dt|date:'d/m/Y H:i' }}</td> </tr> {% endfor %} </tbody> </table> <!--DataTables--> <script type="text/javascript"> $(document).ready( function (){ $('#mytable1').DataTable(); }); </script> <!--Get ID from selected radio button and insert … -
Mysqlclient Installation error in python Django
I try to build a sample project in Pycharm. But In the step migrate classes i face an error. I am using the code python manage.py makemigrations Then terminal shows install mysqlclient. I am using pip install mysqlclient Then shows a error below sreeju@Sreeju:~/PycharmProjects/pythonProject21/SampleProject123$ python manage.py makemigrations Traceback (most recent call last): File "/home/sreeju/PycharmProjects/pythonProject21/venv/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database ModuleNotFoundError: No module named 'MySQLdb' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/sreeju/PycharmProjects/pythonProject21/SampleProject123/manage.py", line 22, in <module> main() File "/home/sreeju/PycharmProjects/pythonProject21/SampleProject123/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/sreeju/PycharmProjects/pythonProject21/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/sreeju/PycharmProjects/pythonProject21/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/home/sreeju/PycharmProjects/pythonProject21/venv/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/sreeju/PycharmProjects/pythonProject21/venv/lib/python3.9/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/sreeju/PycharmProjects/pythonProject21/venv/lib/python3.9/site-packages/django/apps/config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/home/sreeju/PycharmProjects/pythonProject21/venv/lib/python3.9/site-packages/django/contrib/auth/models.py", line 3, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/home/sreeju/PycharmProjects/pythonProject21/venv/lib/python3.9/site-packages/django/contrib/auth/base_user.py", line …