Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get Count of objects by aggregate within Queryset class
i want to get object that is Maximum length/count of ManyToMany Field class Member(models.Model): pass class Chatroom(models.Model): ... members = models.ManyToMany(Member) ... chatRoom = Chatroom.objects.aggregate(Max('members')) ### {'members__max':15} this code does not return an object like:class <QuerySet [object]> but i want to take an object to do something so i did do this room = ChatRoom.objects.aggregate(max_value=Max('members')).get(members__count=max_value) its got an Error : it says there is no __count look up.. could you help me please... -
How to send data to a page in django
<form method="POST"> <select name="sample"> <option>.....</option> </select> </form> Python file def reqData(request): # overhere i want the data selected by the user, and then will iterate that data through my DB to fetch the desired results The web page is going to run on a GET request, but the data that is needed is coming from a POST request, so how to get the data from the select tag. -
Django Heroku error H10 application error .how to solve?
logs 2021-06-12T07:26:16.610575+00:00 heroku[web.1]: State changed from crashed to starting 2021-06-12T07:26:23.217764+00:00 heroku[web.1]: Starting process with command `: gunicorn taskmate.wsgi` 2021-06-12T07:26:26.603659+00:00 heroku[web.1]: Process exited with status 0 2021-06-12T07:26:26.691415+00:00 heroku[web.1]: State changed from starting to crashed 2021-06-12T07:37:24.490756+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=taskmatealex.herokuapp.com request_id=693beacc-8d74-4bc4-afd4-0341b11ea822 fwd="103.70.154.90" dyno= connect= service= status=503 bytes= protocol=https 2021-06-12T07:37:24.916908+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=taskmatealex.herokuapp.com request_id=b83555ff-8575-4642-beba-4b52872555a7 fwd="103.70.154.90" dyno= connect= service= status=503 bytes= protocol=https 2021-06-12T07:38:01.712652+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=taskmatealex.herokuapp.com request_id=5cbe9cee-1f30-4aab-b9ae-591b058c81df fwd="103.70.154.90" dyno= connect= service= status=503 bytes= protocol=https 2021-06-12T07:38:02.265077+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=taskmatealex.herokuapp.com request_id=95a0862c-b752-458d-a1ce-b6a1a2ce0fcd fwd="103.70.154.90" dyno= connect= service= status=503 bytes= protocol=https 2021-06-12T07:38:27.498712+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=taskmatealex.herokuapp.com request_id=ea75b5a5-ef4e-4733-82e0-6dcd08832269 fwd="103.70.154.90" dyno= connect= service= status=503 bytes= protocol=https 2021-06-12T07:38:27.995906+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=taskmatealex.herokuapp.com request_id=798e9b00-ccc8-493d-99b8-eb1fcfb5385a fwd="103.70.154.90" dyno= connect= service= status=503 bytes= protocol=https 2021-06-12T07:40:28.897745+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=taskmatealex.herokuapp.com request_id=0cc3cc67-c96a-46d7-a896-51f8dade44c1 fwd="103.70.154.90" dyno= connect= service= status=503 bytes= protocol=https 2021-06-12T07:40:29.333000+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=taskmatealex.herokuapp.com request_id=f1a671b0-32fe-4c7c-95ed-a4846370315d fwd="103.70.154.90" dyno= connect= service= status=503 bytes= protocol=https my Procfile web: gunicorn taskmate.wsgi wsgi.py file import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'taskmate.settings') application = get_wsgi_application() I did install gunicorn in my virtual env and I have it in … -
Trying to implement Admin model validation
I am a beginner and trying to implement bid system in Django. I want it to work on both Django admin page and and template, therefore I created modelform and modeladmin in Admins.py. models.py: from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class category(models.Model): category = models.CharField(max_length=50, default='SOME STRING') def __str__(self): return f"{self.category}" class bid(models.Model): listing = models.ForeignKey('listing', on_delete=models.CASCADE) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) bid = models.DecimalField(max_digits=6, null=True, decimal_places=2) def __str__(self): return f"{self.user}, {self.listing} {self.bid}" class listing(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) Title = models.CharField(max_length=50) Description = models.CharField(max_length=300) Price = models.DecimalField(max_digits=6, null=True, decimal_places=2) category = models.ForeignKey(category, on_delete=models.CASCADE, related_name="categories") def __str__(self): return f"{self.Title}" admin.py from django.contrib import admin from .models import User, listing, category, bid from django.core.exceptions import ValidationError from django import forms admin.site.register(User) admin.site.register(listing) admin.site.register(category) class bidForm(forms.ModelForm): class Meta: model=bid fields = ['user', 'listing', 'bid'] def clean(self): start_price = self.cleaned_data.get('listing.Price') userbid = self.cleaned_data.get('bid') if userbid <= start_price: raise ValidationError('Please place a bid higher than starting price') return self.cleaned_data class bidAdmin(admin.ModelAdmin): form = bidForm list_display = ('user', 'listing', 'bid') admin.site.register(bid, bidAdmin) It returns the following error: '<=' not supported between instances of 'decimal.Decimal' and 'NoneType'. Also I want to compare instances of previous and current bid on a … -
Django - ModuleNotFoundError: No module named 'alluth'
I encountered an error while trying to make migration. I reinstalled the app yet i still saw the same error. Here is my setting file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # 3rd Party 'rest_framework', 'rest_framework.authtoken', 'allauth', 'allauth.account', 'alluth.socialaccount', 'rest_auth', 'rest_auth.registration', # Local 'posts.apps.PostsConfig', ] # Peculiar to django-allauth app EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' SITE_ID = 1 This is the error am getting when i run python manage.py migrate: ModuleNotFoundError: No module named 'alluth' -
Password Reset Confirm arguments
I am new to django reverse('password_reset_confirm',args=(uid64,token)), I got error in uid64 and token not defined . how to get those value from mail content -
Where is django.contrib.auth.User defined in Django source code
In Django official guide, it reads: Inside this django.contrib.auth model, there is a User class, who has following attributes (username, password, email, first_name, last_name). When I check the source code in github, I did not find this definition in django.contrib.auth. I can only see class AbstractBaseUser(models.Model): in django/contrib/auth/base_user.py on this link, and class User(AbstractUser): in django/contrib/auth/models.py in this webpage. Q1: what does class models.User mean in above official document, it means User is a class under models.py ? Q2: if above is right, then where User class get attributes such as username, email etc? -
AttributeError when trying to created nested serializer in Django REST Framework
I have two models of sets, and cards. Theses models have one to many relationship where there are many cards in a single set. These model are join by a foreign key - each card has set_id which is equal to the id of the set. These IDs are UUID. I am trying to create a serializer using Django REST Framework where I return the details of the set, as well as including all the cards that are part of the set. error Got AttributeError when attempting to get a value for field `cards` on serializer `SetSerializers`. The serializer field might be named incorrectly and not match any attribute or key on the `Set` instance. Original exception text was: 'Set' object has no attribute 'cards'. serializers.py class CardSerializers(serializers.ModelSerializer): class Meta: model = Card fields = ['id', 'number', 'name', 'set_id'] class SetSerializers(serializers.ModelSerializer): cards = CardSerializers() class Meta: model = Set fields = ['id', 'code', 'name', 'releaseDate','cards'] models.py class Set(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ... objects = models.Manager() def __str__(self): return self.name class Card(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ... set = models.ForeignKey(Set, on_delete=models.CASCADE, related_name='Cards', related_query_name='Cards') objects = models.Manager() def __str__(self): return self.name views.py class SetsIndividualData(ListAPIView): serializer_class = SetSerializers def get_queryset(self): … -
Update records in a table from views.py with Django
so basically, I wanted to know how I can change the value of a single field in Django from views.py itself without needing to use forms.py I want to do something like this... def driver_dashboard_trip_completed(request, tripId): trip = Trip.objects.filter(pk=tripId) if trip.exists(): if trip.first().user.id == request.user.id: if trip.first().status == "ACTIVE": trip.first().status = "COMPLETED" else: messages.warning(request, "Invalid access (401 - UNAUTHORIZED)") else: messages.warning(request, 'Invalid Trip details') return redirect('driver_dashboard_rides') But doesn't seem like it works, so is there anything that I am missing out?? This is my models.py... STATUS = [ ('UPCOMING', 'Upcoming'), ('ACTIVE', 'Active'), ('COMPLETED', 'Completed') ] class Trip (models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) departure = models.CharField(max_length=200) arrival = models.CharField(max_length=200) date = models.DateField(validators=[inthe_future]) time = models.TimeField(default=datetime.now().time()) vacant_seats = models.PositiveIntegerField() vehicle_used = models.ForeignKey(Vehicle, on_delete=models.PROTECT) price_per_person = models.IntegerField() status = models.CharField(choices=STATUS, default='UPCOMING', max_length=10) Any help is greatly appreciated thanks! -
Django | Should my Project Make Requests to my Own API?
I have been working on a project for a while. The project consists in a Django API and a Django website that process and shows the data from that API, everything is in the same Django project. I lack of experience running projects in production, so I can't figure out: At what point should I move the API to a separate server or Django project. If it is okey to make requests to the API (which is open to users) from the Django website itself (from the backend of the site). The Django website works on top of the API, so I don't know if I should make request to the API just as a regular user (taking into account that this will increase the requests the server has to handle) or if I should use the code used for the API (thus having the same data but without calling the API endpoints). What do you think is more suitable?* PS: I'm not sure if Stackoverflow is the correct forum for this question, but I think I need perspective from more experienced users. Thanks in advance. -
ContextualVersionConflict Error with PyJWT on installing djangorestframework-simplejwt
I have a digital ocean django instance and after I installed 'djangorestframework-simplejwt' , I am getting Contextual Version Conflict with following error message (PyJWT 1.7.1 (/usr/lib/python3/dist-packages), Requirement.parse('pyjwt<3,>=2'), {'djangorestframework-simplejwt'}) I have upgraded PyJwt to 2+ version and have also removed existing python3-jwt from the instance but with no success. Not sure how and where this 1.7 version is coming from. I have also upgraded the django version to 3+ -
Check empty field value in ajax and django
In my project I am using Ajax to save record because I do not want to load the page for new record. But with below code I want to include the way the I can check the empty value and when some field is empty the record should not be saved. I also want the message informing that the record is saved after the progress bar. Below is the code I am currently use. <script> $(".submit_btn").click(function(){ var form=new FormData($("#ReportForm")[0]); //AJAX CODE var xhr=new XMLHttpRequest(); xhr.onreadystatechange=function(){ if(xhr.status==200){ console.log(xhr.responseText); } } xhr.open("POST","{% url 'report_template_create' %}",true); $("#progressbar").show(); //UPDATING PROGRESS BAR xhr.upload.addEventListener("progress",function(ev){ if(ev.lengthComputable){ var percentage=(ev.loaded/ev.total*100|0); $("#progressbar").css({"width":""+percentage+"%"}).text("Uploading .."+percentage+"%"); console.log(percentage); if(percentage>=100){ location.reload() } } }); xhr.send(form); }) -
Django permissions According to branch ID
I have permissions according branch_id. For example if I have two branches with ids 1 and 2. Also,add,change,view and delete the permissions in every models will be: add_model_name_1,add_model_name_2,change_model_name_1,change_model_name_2 and so on So at increase the branches the performance will be slower and slower. What the best solution for this dilemma. Can I copy authentications apps from Django library to my projects and make foreign key from branch models in permissions models. If I take this in considerations. May I will lose the future update for Django, base to that I need to customize other library that depends on Django permissions likes Django guardian. What about indexes , Could it solve a problems. if it could, How can I make index for Django permissions model. the answer to this question return us to customize Django permissions. who is agree with me make issues for this dilemma. Also who have another solution. -
Path issues in django
I am facing a path issue where after clicking "Login" button which is in /login/ path it looks out for /login/login/ , whereas after clicking the "Login" button I want to return it to my root path. I am attaching the snippets of the code and the snaps, please if somebody comes out with a solution do help. "signup.html file" <form action="signup/" method="post"> {% csrf_token %} <input class="text" type="text" name="username" placeholder="Username" required=""> <input class="text email" type="email" name="email" placeholder="Email" required=""> <input class="text" type="password" name="password1" placeholder="Password" required=""> <input class="text w3lpass" type="password" name="password2" placeholder="Confirm Password" required=""> <input class="text" type="text" name="address" placeholder="Address" required=""> <!-- <div class="wthree-text"> <label class="anim"> <input type="checkbox" class="checkbox" required=""> <span>I Agree To The Terms & Conditions</span> </label> <div class="clear"> </div> </div> --> <input type="submit" value="SIGNUP"> </form> "login.html file" <form action="login/" method="post"> {% csrf_token %} <input class="text" type="text" name="username" placeholder="Username" required=""> <input class="text" type="password" name="password" placeholder="Password" required=""> <input type="submit" value="LOGIN"> </form> "urls.py file" urlpatterns = [ path('',views.signup, name='signup'), path('signup/',views.signup,name='signup'), path('login/',views.login,name='login'), ] "views.py file" from django.shortcuts import render,redirect from django.http import HttpResponse from .models import SignUp from django.contrib.auth.models import auth # Create your views here. def login(request): if request.method == 'POST': username= request.POST['username'] password= request.POST['password'] user = auth.authenticate(username=username,password=password) if user is not None: … -
python string variable changes '\b' into '\x08' and '\a' into '\x07' and similarly for some number and characters too? why?
when I am using -> filename="media\documents\dog_bark.wav" the python works fine and my intended functionality works but with -> filename="media\documents\afile1.wav", filename="media\documents\732-20.wav" and similar other selected filepath it's changing the first character of filename to some x07, x08 and so on why does this happen and any solution of this? Thank You! -
Chat web application using video ,audio and text for communication
I want to develop a website in which users can have video chat and they can connect to other user anonymously without had been added by the other person as friend. I also want that all the active users list is displayed on the website. So somebody please suggest me how can I implement it on django on the back end and react on the frontend? -
ModuleNotFoundError: no module name 'mysite.settings'
I have been trying to deploy my django project on heroku and have been butting my head against this error for a week. everything runs fine locally but when i push to heroku, all i get is an application error with this information in heroku logs --tail 2021-06-12T04:09:09.270161+00:00 heroku[web.1]: State changed from crashed to starting 2021-06-12T04:09:12.000000+00:00 app[api]: Build succeeded 2021-06-12T04:09:17.474951+00:00 heroku[web.1]: Starting process with command `gunicorn mysite.mysite.wsgi` 2021-06-12T04:09:20.249454+00:00 app[web.1]: [2021-06-12 04:09:20 +0000] [4] [INFO] Starting gunicorn 20.1.0 2021-06-12T04:09:20.250347+00:00 app[web.1]: [2021-06-12 04:09:20 +0000] [4] [INFO] Listening at: http://0.0.0.0:48385 (4) 2021-06-12T04:09:20.250492+00:00 app[web.1]: [2021-06-12 04:09:20 +0000] [4] [INFO] Using worker: sync 2021-06-12T04:09:20.255741+00:00 app[web.1]: [2021-06-12 04:09:20 +0000] [8] [INFO] Booting worker with pid: 8 2021-06-12T04:09:20.275136+00:00 app[web.1]: [2021-06-12 04:09:20 +0000] [9] [INFO] Booting worker with pid: 9 2021-06-12T04:09:20.462240+00:00 app[web.1]: [2021-06-12 04:09:20 +0000] [8] [ERROR] Exception in worker process 2021-06-12T04:09:20.462242+00:00 app[web.1]: Traceback (most recent call last): 2021-06-12T04:09:20.462243+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker 2021-06-12T04:09:20.462243+00:00 app[web.1]: worker.init_process() 2021-06-12T04:09:20.462244+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 134, in init_process 2021-06-12T04:09:20.462244+00:00 app[web.1]: self.load_wsgi() 2021-06-12T04:09:20.462245+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi 2021-06-12T04:09:20.462245+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2021-06-12T04:09:20.462245+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi 2021-06-12T04:09:20.462246+00:00 app[web.1]: self.callable = self.load() 2021-06-12T04:09:20.462246+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 58, in load 2021-06-12T04:09:20.462247+00:00 app[web.1]: return self.load_wsgiapp() … -
Setting Font-Family (Django + Bootstrap)
Currently have the following CSS stylesheet which should apply Courier New to a, p, h1, h2, etc... a, p, h1, h2, h3, h4, h5, h6 { font-family: "Courier New"; color: #54627B; } My a tags are showing as Courier New. However, the Font-Family for my h1 are not. They are showing up as: -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji" It looks like Bootstrap is overriding the Font Family (even though it should not; my custom stylesheet is declared after the Bootstrap one) <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'blog_post_app/base.css' %}"> -
django model instance value set to none after the loop
Here, in the rename_dfs function, I am getting the Documents_details model instance and setting its corresponding fields inside the loop. Inside the for loop, some instance field values are getting set, but after the for loop, the instance field value automatically set to None. def rename_dfs(documentId, request): doc_details = Documents_details.objects.get(id=documentId) for key, value in request.items(): if request[key] and key != 'csrfmiddlewaretoken': if re.search("_a$", key): doc_details.key = int(value) print(key, doc_details.key) if re.search("_b$", key): doc_details.key = int(value) print(key, doc_details.key) print(doc_details.document_date_a) doc_details.save() Output: document_date_a 7 invoice_no_a 5 invoice_type_a 3 narration_a 2 debit_credit_a 1 document_date_b 5 invoice_no_b 4 invoice_type_b 3 narration_b 2 debit_credit_b 1 None # last print statement after the loop Model: class Documents_details(models.Model): company_name_a = models.CharField(max_length=50) document_date_a = models.IntegerField(null=True, blank=True) posting_date_a = models.IntegerField(null=True, blank=True) invoice_no_a = models.IntegerField(null=True, blank=True) invoice_type_a = models.IntegerField(null=True, blank=True) narration_a = models.IntegerField(null=True, blank=True) debit_a = models.IntegerField(null=True, blank=True) credit_a = models.IntegerField(null=True, blank=True) debit_credit_a = models.IntegerField(null=True, blank=True) company_name_b = models.CharField(max_length=50) document_date_b = models.IntegerField(null=True, blank=True) posting_date_b = models.IntegerField(null=True, blank=True) invoice_no_b = models.IntegerField(null=True, blank=True) invoice_type_b = models.IntegerField(null=True, blank=True) narration_b = models.IntegerField(null=True, blank=True) debit_b = models.IntegerField(null=True, blank=True) credit_b = models.IntegerField(null=True, blank=True) debit_credit_b = models.IntegerField(null=True, blank=True) documents = models.ForeignKey(Documents, on_delete=models.CASCADE) Thanks in advance -
What is the recommended configuration for two web apps served by Apache Virtual Hosts in AWS VPC?
I have a VPC with one public and one private subnet. The idea is having a website and REST API in the public subnet (EC2 instance) and have the RDS MySQL instance in the private subnet. Currently I have my website running with a specific domain (with its own virtualhost config) but I'm not sure how to procede with the API deployment and its own config. Should the ServerName be the private EC2 IP address? I've have never done this and would like to know a recommended approach. -
How can I pass input field value to function in views.py file
I am trying to update my password.For that email-id ,new password and confirm new password values are passed to views.py function by POST method.But POST method does not pass any value to views.py function.Also I tried to validate the form using JAVASCRIPT,but I failed to do that.How can I rectify this problem.Can anyone help? HTML file: <!DOCTYPE html> <html lang="en"> {% load static %} <head> <meta charset="UTF-8"> <title>Password Reset</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link href="{% static 'styles/style.css' %}" rel="stylesheet"/> </head> <body> <section class="sflog" id="sflog"> <div class="container-fluid"> <div class="row"> <div class="col-12" id="std"> <form method="POST" name="forgot" action="{% url 'ufpasswordreset' %}"> {%csrf_token%} <center> <h3>Password <span>Reset</span> Form</h3><br> </center> <label style="color:white;padding-left:13%;">Enter Your Registered Email</label> <center> <input type="email" id="email" name="email" placeholder="Email"><br><br> <span id="lemail"></span> </center> <label style="color:white;padding-left:13%;">Enter New Password</label> <center> <input type="password" id="pass" name="pass" placeholder="New Password"><br><br> <span id="lpass"></span> </center> <label style="color:white;padding-left:13%;">Confirm New Password</label> <center> <input type="password" id="cpass" name="cpass" placeholder="Confirm New Password"><br><br> <span id="lcpass"></span> </center> <center> <button type="submit" name="submit" onclick="return reset()">Submit</button><br><br><br><br> </center> </form> </div> </div> </div> </section> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <script src="{% static 'js/scriptfunction.js' %}"></script> </body> </html> views.py def user_forgot_password_reset(request): if request.method == 'POST': print("hi") femail = request.POST.get('email') print(femail) fpassword = request.POST.get('pass') print(fpassword) fepassword = sha256(fpassword.encode()).hexdigest() fcpassword = … -
How to create a web app that deploys AI in the back end?
So I've created an AI model that analyzes music and tries to figure out what notes are played in Python. I want to create a web-app like this: https://piano2notes.com/en The web-app mentioned above allows a user to upload a song or link a song from YouTube and then some AI magic happens in the background. How could I create this? I'm still kinds new to making web apps but from the research I have done I've come to the conclusion that this is what I should use: React for front-end and UI Django for back-end Firebase for database Do these technologies 'fit' for what I am trying to do? Thanks in advance :) -
python: if condition, it is very simple calculation, but it does not work
I wrote very simple calculation function as below; def price_cal(): if direction == 'A' and (int(no_of_passenger) == 1): return int(suburbs.get(suburb)) + (int(no_of_passenger) * 10) elif direction == 'A' and (1 < int(no_of_passenger) <= 9): return int(suburbs.get(suburb)) + (int(no_of_passenger) * 10) - 10 elif direction == 'A' and (9 < int(no_of_passenger) <= 13): return int(suburbs.get(suburb)) + (int(no_of_passenger) * 10) + 20 elif direction == 'B' and (int(no_of_passenger) == 1): return int(suburbs.get(suburb)) + (int(no_of_passenger) * 10) + 10 elif direction == 'B' and (1 < int(no_of_passenger) <= 9): return int(suburbs.get(suburb)) + (int(no_of_passenger) * 10) else: return int(suburbs.get(suburb)) + (int(no_of_passenger) * 10) + 20 price_cal() When I run this function, only I get right answers from the first if direction == 'A' and (int(no_of_passenger) == 1): return int(suburbs.get(suburb)) + (int(no_of_passenger) * 10) the rest of them, I get only answers from the last function else: return int(suburbs.get(suburb)) + (int(no_of_passenger) * 10) + 20 I don't know why this happen... please correct this simple function, much appreciated -
How to set filter attributes in __init__
I know how to set the attributes for form fields with something like class CaseRegistrationForm(ModelForm): ... def __init__(self, *args, **kwargs): ... self.fields["subject"] = forms.ModelMultipleChoiceField( queryset=Subject.objects.all(), widget=forms.CheckboxSelectMultiple, ) How do I do the equivalent for filters? I have tried something similar for filters: class CaseFilter(django_filters.FilterSet): ... def __init__(self, *args, **kwargs): ... self.fields["subject"].label = "Role:" but 'CaseFilter' object has no attribute 'fields' -
Python Django: AttributeError: 'int' object has no attribute 'timetuple'
Quick note: this error may be somewhat linked to this thread, but the use case and python version (the other one is still at v2) is different. Other similar threads don't regard specifically to python datetime. I have the following code: import datetime from .models import RaceData, RacerData @periodic_task(crontab(minute='*/15')) def record_racedata(): team = nitrotype.Team('PR2W') timestamp = datetime.datetime.now() # timestamp for members in team.data["members"]: rcd = RaceData( timestamp=timestamp, ) rcd.save() @periodic_task(crontab(minute='*/15')) def record_racerdata(): timestamp = datetime.datetime.now() # timestamp for members in team.data["members"]: rcrd = RacerData( timestamp=timestamp, ) rcrd.save() # error comes from here models: class RaceData(models.Model): id = models.BigAutoField(primary_key=True) timestamp = UnixDateTimeField() class RacerData(models.Model): id = models.BigAutoField(primary_key=True) timestamp = UnixDateTimeField() And I get the following output: AttributeError: 'int' object has no attribute 'timetuple' What confuses me the most is how the first inclusion of timestamp doesn't come with an error, but maybe the execution doesn't go from top to bottom. Either way, I believe that I've initialized the timestamp variable appropriately. Can anyone please help? Note that I cannot define timestamp outside either function because I need the timestamp to be constantly updated with the periodically-called functions. EDIT I've seen elsewhere that this error occurred because the namespace datetime was used …