Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why django authenticate() always returns None to MySQL database? [closed]
i have MySQL database that is connected to my Django project, and i want to authenticate user using authenticate(), but the result of it always returning None. this is code of my django project: these forms uses 'User' model and its connected to MySQL 'loginView' handels login request and authenticate user and for password hashing problem, in MySQL database it's showed as plaintext password: password column in user_auth table even if i only authenticate username it still gives me None. -
form tags automatically closing
I am trying to validator with jsquery validator plugin. but it doesn't working. Now I found in chorme dev tools, tag is closed automatically! It seems to be related to the for loop in Django. Why does the form tags closed automatically? what's wrong with my script? In my .html codes, <div class="container-box"> <div> <table class="table table-striped tc"> <div style="float: right; padding: 1%"> <p style="width: 40%; float: left; font-weight: bold">Register for My rate :</p> <input type="text" style="border-radius: 5px; width: 30%; float: left" class="inputgroup form-control form-control-sm tc" placeholder="group" /> <button class="btn btn-outline-primary btn-sm sendgroup" style="float: right; width: 30%">Register</button> </div> <thead class="table"> <tr> <td>Origin</td> <td>Dest</td> <td>Name</td> <td>Cur</td> <td>Rate</td> <td>Unit</td> <td>ChargeAt</td> <td>Group</td> <td>U/D</td> </tr> </thead> <tbody class="tbody"> {% for i in info %} <form id="UpdateForm{{i.id}}"> <tr class="tr{{i.id}}"> <td><input type="text" value="{{i.origin}}" class="origin{{i.id}} tc form-control form-control-sm" disabled name="udtorigin" /></td> <td><input type="text" value="{{i.dest}}" class="dest{{i.id}} tc form-control form-control-sm" disabled name="udtdest" /></td> <td><input type="text" value="{{i.name}}" class="name{{i.id}} tc form-control form-control-sm" disabled name="udtname" /></td> <td> <select id="cur" class="cur{{i.id}} tc form-select form-select-sm" disabled name="udtcur"> <option value="{{i.cur}}">{{i.cur}}</option> <option value="====">====</option> <option value="USD">USD</option> <option value="KRW">KRW</option> </select> </td> <td><input type="text" value="{{i.rate}}" class="rate{{i.id}} tc form-control form-control-sm" disabled name="udtrate" /></td> <td> <select id="unit" class="unit{{i.id}} tc form-select form-select-sm" disabled name="udtunit"> <option value="{{i.unit}}">{{i.unit}}</option> <option value="====">====</option> <option value="R/TON">R/TON</option> <option value="BL">BL</option> … -
Adding to database from another database using button in django
I am creating a web application in which there is a lot of data displayed in tables. I wanted to create a platform where there are various documents, and in order to see them, the user has to send a request for access. Meaning it browses what documents are available and asks for access to see their details. Now I've run into a problem that I can't solve. I want to add data from one table to another without form. Only by clicking a button in a table row (this is the "request for access"). The data in that row would be added to another table. Unfortunately, when I click the button, nothing happens. I know I'm probably going about this the wrong way, but when no problem is displayed, the page reloads normally, I don't have any ideas how to solve it. I created models: class CourtFile(models.Model): court = models.ForeignKey(Court, on_delete=models.CASCADE, null=True) signature = models.CharField(max_length=200, null=True) article = models.CharField(max_length=200, null=True) contents_list = models.FileField(upload_to = "filepath", null=True) def __str__(self): return f'{self.court} - {self.signature}' class AccessRequest(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) status = models.BooleanField(null=True) signature = models.ForeignKey(CourtFile, on_delete=models.CASCADE, null=True) def __str__(self): return f'{self.signature}' I am displaying the table like this: <tbody> … -
How to call multiple API and render the response of all those API in a template in django
I tried rendering the response of multiple API in a single template but since once one view can we passed in the path, i am unable to think of what i can do I tried keeping the two functions to call the API inside a class but i got GET 405 error -
Live Stream text to html tamplets from Django
i have a function at the backend in django that calculate and return frames speed of a video given to OpenCv.videoCapture() .the type of the speed is float . class video_feed(object): def __init__(self, pathVideo): self.cap = cv.VideoCapture(pathVideo) #some code ..... def __del__(self): self.cap.release() def get_frames(self): #some code ... return speed_list this method keep calling the method while the video is working : def gen_speed(video_feed): print('this is spped generation method') while True: speed = video_feed.get_frames() yield(speed) @gzip.gzip_page def speed_frame(request): try: pathVideo = "video_detection/statics/rl4_pb8-7.mp4" cam = model.video_feed(pathVideo) #return StreamingHttpResponse(model.gen_test(cam),content_type="text/csv") return HttpResponse({'speed':cam.get_frames()}) except: print("speed_frame not working !!!!!!!!!!!!!!!!!!!!!!!!") but this code doesn't work . i need a way to make the speed stream to my html page so i can use it in a chartjs. streaming video using openCv is woking just fine but when i change the type to float it doesn't work . -
Django - Accessing extra ModelForm fields in a different template
I have a first view (createview) which calls a ModelForm that has an extra field added to it. The first view leads to a second view (detailview), where i need to access the fields from the previous ModelForm to show them in the template. For the fields belonging to the model, i used {{ object.fieldname }} in the template and it works. The problem that remains is how to access the field i added myself. Thank you for your help -
Upload File in a folder without using submit button in Django
I am on a Django project and the scenario is that I want to save file in a folder without clicking on submit button. I am already saving the file in a folder with the help of submit button but now the scenario has changed and now I want to save file without clicking on submit button. Here are the details of my files: views.py: def compliance_check(request):` if request.method == 'POST':` uploaded_file = request.FILES['doc']` print(uploaded_file.name)` print(uploaded_file.size)` fs = FileSystemStorage()` fs.save(uploaded_file.name, uploaded_file)` messages.info(request, 'your file ' + uploaded_file.name + " has been uploaded successfully") return render(request, 'enroll/abc.html') upload.html: <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" id="file" name="doc"> <input type="submit" name = "doc" value="upload file" class="btn btn-warning btn-sm" disabled /> </form> settings.py: STATIC_URL = '/static/' MEDIA_ROOT = os.path.join('/home/t/Desktop/folder name') MEDIA_URL = '/upload/' urls.py: path('compliance_check/', views.compliance_check, name='compliance check'), Now the situation is that I am already saving file in a folder. But, now, I want to save file without clicking on submit button. -
how to save data from API whenever it updates (django)
there is an API that comes from a device. This device updates its sampling variables every 2 minutes , maybe the results change or may not(because of some conditions). i want to store this API exactly whenever the device updates itself. i have tried using background tasks with 2 minutes intervals but for example the latest result doesn't match the API at the moment , because of the delay which is convincing. I am just curious to know is it possible to store the data as soon as the device updates itself? -
Django - Send email with URL to newly uploaded file
I have a Django app where users can upload PDF files. The PDF files will be saved on my cloud provider. After successfully submitting the PDF, I want to send an email to the user with the URL to the PDF on my cloud. I've been trying to do it by overriding form_valid() but at that point, the URL is not yet generated. The URL also isn't hardcoded, so I can't just point to a hard coded URL in form_valid() Any ideas on how to solve this? -
two packages require two different python versions on django deployment on centos7?
I'm trying to deploy my django project on Centos 7. While installing pip -r install requirements.txt I got error and I somehow tried to solve it. First of all it is said that asgiref==3.5.0 can't be installed in Python 3.7 below. Default installed python version is 3.6.8. Then I install python 3.7 and asgiref problem is solved, but I got another error on coreschema==0.0.4 (which is in requirements.txt). I upload image below, but looking at pypi I thought that coreschema is not supported on python 3.6 above. If this is the issue, how to solve it? It is possible to install coreschema with pip or pip3, because their python version is below than 3.7 -
Yum Cache failed. Error : amzn2-core/2/x86_64/group_gz FAILED
Can anyone help here when I deploy an EC2 instance on aws when yum makecache: amzn2-core | 3.7 kB 00:00:00 amzn2extra-docker | 3.0 kB 00:00:00 amzn2extra-nginx1 | 3.0 kB 00:00:00 amzn2extra-postgresql11 | 3.0 kB 00:00:00 amzn2extra-python3.8 | 3.0 kB 00:00:00 amzn2-core/2/x86_64/group_gz FAILED https://amazonlinux-2-repos-eu-central-1.s3.dualstack.eu-central-1.amazonaws.com/2/core/2.0/x86_64/da64f79d533a70e6036c814aff5d1e823eeeb815054a7a3785d2d5198ff2eabc/repodata/comps.xml.gz?instance_id=i-08792031e5dac83de&region=eu-central-1: [Errno 14] curl#6 - "getaddrinfo() thread failed to start" Trying other mirror. amzn2-core/2/x86_64/filelists_ FAILED https://amazonlinux-2-repos-eu-central-1.s3.dualstack.eu-central-1.amazonaws.com/2/core/2.0/x86_64/da64f79d533a70e6036c814aff5d1e823eeeb815054a7a3785d2d5198ff2eabc/repodata/filelists.sqlite.gz?instance_id=i-08792031e5dac83de&region=eu-central-1: [Errno 14] curl#6 - "getaddrinfo() thread failed to start" Trying other mirror. amzn2-core/2/x86_64/updateinfo FAILED https://amazonlinux-2-repos-eu-central-1.s3.dualstack.eu-central-1.amazonaws.com/2/core/2.0/x86_64/da64f79d533a70e6036c814aff5d1e823eeeb815054a7a3785d2d5198ff2eabc/repodata/updateinfo.xml.gz?instance_id=i-08792031e5dac83de&region=eu-central-1: [Errno 14] curl#6 - "getaddrinfo() thread failed to start" Trying other mirror. (1/21): amzn2-core/2/x86_64/primary_db | 66 MB 00:00:03 (2/21): amzn2-core/2/x86_64/other_db | 505 B 00:00:00 no mem for new parser Traceback (most recent call last): File "/usr/libexec/urlgrabber-ext-down", line 22, in <module> from urlgrabber.grabber import \ File "/usr/lib/python2.7/site-packages/urlgrabber/__init__.py", line 55, in <module> from grabber import urlgrab, urlopen, urlread File "/usr/lib/python2.7/site-packages/urlgrabber/grabber.py", line 543, in <module> import urllib File "/usr/lib64/python2.7/urllib.py", line 1225, in <module> for a in _hexdig for b in _hexdig) MemoryError Traceback (most recent call last): File "/usr/libexec/urlgrabber-ext-down", line 22, in <module> Traceback (most recent call last): File "/usr/libexec/urlgrabber-ext-down", line 22, in <module> from urlgrabber.grabber import \ File "/usr/lib/python2.7/site-packages/urlgrabber/__init__.py", line 55, in <module> from urlgrabber.grabber import \ File "/usr/lib/python2.7/site-packages/urlgrabber/__init__.py", line 55, in <module> from grabber import urlgrab, urlopen, urlread … -
Fetch ((response) => {response.json()} replacing page with Json in Django App [closed]
I'm calling Fetch in a django app and it's getting the dict that I want, but it ends up replacing my page with the dict. I think I've written something wrong in the fetch call, but I'm not entirely sure cause it's my first time using fetch. Please help! I've been watching tutorials for two days now around Ajax and Fetch! Does anyone know what is happening here? Any help would be greatly appreciated! My page ends up like this after getting the response.json() which is correct cause that's what it's supposed to return as shown here in the views It's just supposed to return that one thing, total_votes .views def vote(request, poopfact_id): ... data = {"total_votes": total_votes} return JsonResponse(data, safe=False) I think the issue is here somewhere, does someone know if I'm missing something? .script fetch(url, { method: 'POST', credentials: 'same-origin', headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest', 'X-CSRFToken': csrftoken, } body: JSON.stringify(data) }); .then((response) => { response.json() }); .then((data) => { console.log(data) }); .catch((error) => { console.log(error) }); -
Checking Form Uploading Progress in Django
Is it possible to track the user form upload progress in the current page before browser redirects to the form's actions attribute? In Django's template, I have a form like below; It accepts user data such as name, age and multiple images from input field. If I upload large image here, I need to wait for more time before it redirects to success page. If i can see progress bar or something that confirms the remaining time for form's successful submission page, it will be better {% extends "base.html" %} {% block content %} {% if form.errors %} <p style="color: red;"> Please correct the error{{ form.errors|pluralize }} below. </p> {% endif %} <div data-role="content" style="padding: 15px"> <form action="{% url success %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.errors }} {{ form.non_field_errors }} {{ form.as_table }} <input type="submit" value="Submit" id="Save"> </form> </div> {% endblock %} -
I'm doing a study assignment. when checking, the teacher made a remark, what did he mean?
` I'm doing a study assignment. when checking, the teacher made a remark, what did he mean? I left a comment in the code ''' Views for 'users' API application. ''' class SubscriptionsViewSet(viewsets.GenericViewSet): ''' ViewSet for user subscription actions. ''' serializer_class = UserSubscriptionSerializer def get_queryset(self): return self.request.user.subscriptions.all() @action(detail=True, methods=['post', 'delete'], name='subscribe') def subscribe(self, request, pk=None): ''' Process user subscription actions.. ''' subscribed = get_object_or_404(get_user_model(), id=pk) if self.request.method == 'DELETE': request.user.subscriptions.remove(subscribed) return Response(status=status.HTTP_204_NO_CONTENT) if request.user.subscriptions.filter(id=subscribed.id).exist(): #! Here, most likely, you need to return Response raise validators.ValidationError( _('The subscription already exists.') ) request.user.subscriptions.add(subscribed) serializer = self.get_serializer(instance=subscribed) return Response(serializer.data, status=status.HTTP_201_CREATED) ` -
How to get data from terminal Python Django
I have a Django application in which, on the click of a html button, I launch a third-party Python script. This script in the terminal displays a lot of information - messages, progress bar, and more. How can I intercept this information for later display on the pages of the Django web application? How, for example, to save this information to a file? Help me to understand. I don't even have ideas. I dug into the code of a third-party script, but I can’t understand how information is displayed there in the terminal. -
TypeError: Unable to serialize datetime.time. Django, Dsl elasticsearch, Python
i have a document with late_delivery = ObJectField() "City": { "delivery_time": TimeField, "order_time": TimeField, } example: "late_delivery": { "SomeCity": { "delivery_time": "23:00:00", "order_time": "22:00:00", }, and i wanna filter queryset by datetime.time, that less than now i tried class LateDeliveryFilter(BaseFilterBackend): def filter_queryset(self, request, queryset, view): late_delivery_requested = request.data.get("late_delivery", None) if not late_delivery_requested: return queryset now = datetime.now().time() queryset = queryset.filter(fulfillment=RB_STOCK) kwargs = { f"late_delivery__{settings.CITY_NAME}__order_time": {"lt": now} } return queryset.filter("range", **kwargs) but i'm getting an error TypeError("Unable to serialize datetime.time(12, 51, 22, 708584) (type: <class 'datetime.time'>)")) can anyone help with this? -
Create a shopping cart in Django Rest Framework
I want to implement shopping cart in Django Rest Framework. I store information about the shopping cart inside the models. I don't want to use a session for this and I want to save it in the database. users must be logged in to create and add products to the cart. But I want them to be able to add the product to the cart without logging in. I would be very grateful if you could guide me. Thanks My Model : class Cart(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() My View: class AddToCartApi(APIView): serializer_class = AddToCartSerializer permission_classes = [IsAuthenticated] def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) user_id = request.user.id data = serializer.validated_data Cart.objects.create( user_id=user_id, product_id=data['product_id'], quantity=data['quantity'], ) return Response(....) -
Trying to understand how sql query is generated by django framework?
I am using django debugger in pycharm to see how ORM does the magic. I have a simple model and a very basic query. Model.objects.get(id=1). The first step in click (debugger) takes me to django.db.models.manager.py. The get method of ManagerDescriptor class in this module is called. Then the pointer goes to django.db.models.query and as soon as the init method is complete the query is generated out of nowhere. Where did the query select Model.name, Model.age ... from Model come from? I am sure I am missing something here, if anyone knows the internal working or can direct me to any tutorials on this please guide me. Thank you Model.objects.get(id=1) -
Does not get the url from reverse with DRF DefaultRouter
I am trying to get the urls for writing the tests using the reverse function. But I'm getting the error Errors :- Reverse for 'notes' not found. 'notes' is not a valid view function or pattern name. urls.py file from django.contrib import admin from django.urls import path, include from core import views from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register("notes",views.NoteModelViewSet) urlpatterns = [ path("",include(router.urls)), ] and test.py file def test_get_all_notes_path(self): url = reverse('notes') response = self.client.get(url) self.assertEqual(response.status_code, 200) I'm getting error for line url = reverse('notes') that I have mentioned above. My Model and routes everything working fine. Only I'm not get the url in reverse funtion. -
In Django Template how to get all grand child object using single object?
I have a models like : class Invoice(models.Model): created_date = models.DateTimeField(auto_now_add=True) class Sell(models.Model): invoice = models.OneToOneField(Invoice, on_delete=models.CASCADE) class SellItems(models.Model): sell = models.ForeignKey( Sell, related_name='sell_item', on_delete=models.CASCADE) item = models.CharField(max_length=200) In template, how can I get SellItems using Invoice object. -
NameError at /register name 'random_key' is not defined
Environment: Request Method: GET Request URL: http://127.0.0.1:8000/register Django Version: 4.1.3 Python Version: 3.11.0 Installed Applications: ['ritpay', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', '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'] Traceback (most recent call last): File "C:\Users\Manoj\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\Manoj\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Manoj\Desktop\ritconnwallet\ritpay\views.py", line 84, in register private_key = random_key(private_key) Exception Type: NameError at /register Exception Value: name 'random_key' is not defined import random_key.. I am currently developing a blockchain wallet with python. My register page is not loading and i am not getting any public address and i cannot register any new user. When i load the register.htm , the page says random_key is not defined. -
How can i create unique together based on a field in Django
This is my code class Address(models.Model): customer = models.ForeignKey(Customer, related_name='addresses', on_delete=models.CASCADE) lat = models.FloatField() long = models.FloatField() class Meta: constraints = [ UniqueConstraint(fields=['lat', 'long'], name='lat_long_unique') I want the field lat long unique together but just with the same customer, how can i achieve that? -
save data to database from multiple APIs django
there are over 20 APIs that are differentiated by name query string argument at the end of them like:(https/.../?name=121). now i am just hard coding them in my code for example: response1 = requests.get ..... response2 = requests.get ..... with this approach i should write 20 lines .is there any better way to do this? note: i need all these APIs at the same time cause they get updated every 5 minutes and i should store them into database separately -
How to save Django Form and Formset at the same time
I have page in which I use a form and formset at the same time. The form is for the thesis information and the formset if for the author. This the code in my models.py ` class thesisDB(Model): thesis_id = models.AutoField(primary_key=True, blank=True, null=False) title = models.CharField(max_length=200, blank=True, null=True, unique=True) published_date = models.DateField(blank=True, null=True) pdf = models.FileField(upload_to='pdf/', blank=True, null=True ,validators=[FileExtensionValidator(['pdf'])],) course = models.ForeignKey(ColCourse, default=None, on_delete=models.CASCADE, verbose_name='Course') tags = TaggableManager() date_created = models.DateField(auto_now_add=True, blank=True, null=True ) uploaded_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=None) published_status = models.CharField(max_length=10, choices= THESIS_DECISION, default='Pending') abstract = models.TextField(blank=True, null=True) hit_count_generic = GenericRelation(HitCount, object_id_field='object_pk', related_query_name='hit_count_generic_relation') reason = models.TextField(blank=True, null=True) slug = models.SlugField(max_length = 250, null = True, blank = True) def save(self, *args, **kwargs): self.title = self.title.title() #self.author = self.author.title() self.slug = slugify(self.title + "-" + self.author + "-" + str(self.published_date)) super().save(*args, **kwargs) class Meta: db_table = 'thesis_storage' initial_validator = RegexValidator('[A-Z]+.', 'Initial must contain period') class Authors(Model): thesis = models.ForeignKey(thesisDB, on_delete=models.CASCADE) first_name = models.CharField(max_length=200, blank=True, null=True) last_name = models.CharField(max_length=200, blank=True, null=True) middle_initial = models.CharField(max_length=2, blank=True, null=True, validators=[initial_validator]) ` This is the code in my forms.py ` class AuthorForm(forms.ModelForm): class Meta: model = Authors exclude = () widgets = { 'first_name': forms.TextInput(attrs= {'placeholder': 'First Name', 'class':'form-control', 'required': 'required'}), 'last_name': forms.TextInput(attrs= {'placeholder': 'Last … -
{% load gTTS %} in template make mistake 'gTTS' is not a registered tag library
hi everybody i make a quiz with django i want to add text to speech advantage with google i recive erroe mesaage gTTS' is not a registered tag library when i write in template {% load gTTS %} <audio src="{% say 'en-us' {{question.question}} %}" controls i install gTTS and i add aline in setting.py INSTALLED_APPS = [ 'gTTS', i make the application without any code i depend in this page enter link description here why did not work