Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to implement automatically send email when MySQL column get updated (django+MySql)
I have models like Id, Name, email, Status. And created serializers and views. I am updating the Status values by PUT method. How to implement an automatic email notification to smtp.example.com with the changed Status value. Ex: Status column value is 'abc' I am updating value 'abc' to 'xyz' using PUT. I want an email should automatically send to particular email-id belongs to that row using primary key Id. -
Pass request URL parameter into create view
I am hoping this is a simple tweak. I've been reading through various threads here but I am missing a very basic step -- how do I grab the argument from the URL request? For instance, the URL is http://127.0.0.1:8000/registration/student/item/create/8 URL definition is path('student/item/create/<int:pk>',views.CreateStudentBehaviorItem.as_view(),name='student_item_create'), My class view is as follows: class CreateStudentBehaviorItem(LoginRequiredMixin, generic.CreateView): model = StudentItem form_class = StudentItemForm success_url = reverse_lazy('registration:student_item_list') def get_form_kwargs(self): kwargs = super(CreateStudentBehaviorItem, self).get_form_kwargs() kwargs['pk'] = self.request.GET.get('pk') return kwargs The form is: class StudentItemForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.course = kwargs.pop('pk', 'all') super().__init__(*args, **kwargs) # Begin filtering by course ID class Meta: model = StudentItem fields = ("item_student","behavior_category","behavior_item","response","internal_comments") widgets = { 'item_student': forms.Select(attrs={'class': 'form-control'}), 'behavior_category': forms.Select(attrs={'class': 'form-control'}), 'behavior_item': forms.Select(attrs={'class': 'form-control'}), 'response': forms.Select(attrs={'class': 'form-control'}), 'internal_comments': forms.Textarea(attrs={'class': 'form-control', 'rows':5}), } I haven't even gotten to the point to filter because I can't seem to get the PK from the request URL. My minimal Django experience is with get_context_data to grab request URL details. I hope this is a simple correction to grab the value. I appreciate it. -
Django deployment on Heroku failed due to "ModuleNotFoundError at / No module named '_tkinter'"
I'm trying to deploy my Django app to Heroku and this error faced me on deployment I'm not using tkinter anywhere on my app of course and the stack trace does not point to my app the app is running with no issues locally -
ProgrammingError at /admin/patients/appointment/ column patients_appointment.date does not exist
I am facing the above error, even though the "date" column is there in the model. class Appointment(models.Model): name=models.ForeignKey(Patient, on_delete=CASCADE) doctor=models.ForeignKey(DoctorDetail, on_delete=CASCADE) start_time=models.TimeField() end_time=models.TimeField() date=models.DateField() def __str__(self): return self.name.name This was the error I was facing: -
Django Multiple Databases for Different Users
I'm wondering if it's possible to use multiple databases for different users in the same app? I've read about the multiple database documents and searched a lot online but could'nt found any tutorial for it. Is there any way to use different databases for different users in the same app ? -
Django with Postgres - Unique Constraint for One Tenant in Multitenant Database
I've been reading and reading and reading, but finally decided to shortlist my questions regarding multitenant Postgres with Django. I'm quite new with using Django, so please bear with me. We are developing a multitenant business platform with more than 300 tables. For tenants' ids, we have chosen UUID4, so there are my questions coming: Is it enough to use UUID4 for tenants' and users' ids only and then reference them as foreign keys in every other table? If not, Is there a need to use UUID4 in every table? That means that pk in each table will be UUID and that table will have all foreign keys as UUID4s as well.... The second solution would be the UUID4 for tenants' and users' pks only. Other tables would have bigint pks and only 2 foreign keys as UUID (tenant & user). In some tables, we need to have other unique data than just pk (such as names, document numbers, tax data and so on). Is there a way to determine/check the uniqueness of such data in a tenant dataset by db constraint or should that be solved by code? The data volume and number of tenants and users are in … -
How to get ids of the objects from django model?
How to get ids of the objects from the model. qs = Society.objects.all() cityID = City.objects.get(pk=1) The above query will return only one object whose id is 1. but I need all cities id so that can I access the city's names from id as you can see in below code. for s in qs: ... s_name = qs.filter(name__iendswith=cityID.name) ... break -
Live Recording -- saving to google cloud storage -- is it possible
i am wondering is there any possibility of uplaoding the live stream or recording to the google storage frame by frame with audio and video, aws is having the live recording storage options but i am not finding any good resources with the google cloud storage. is there any one out there who can help me with this problem? Thanks in advance. -
Django ajax url not reading
I have an ajax file which calls the url from the urls.py which gets the json data from the views.py but when I run the server it just shows Not Found:/dept-json/ I did manage to get it to work using the django snippet {% url 'accounts:dept-json'%} However I do not want this since I need to get and pass the variable from the dept-json data to another ajax url which is: url:`/prog-data/${selectedDept}/` I have read here that you can't pass variables in ajax like {% url 'accounts:prog-json' department%} how do I manage to do this? here is my code: main.js $.ajax({ type: 'GET', url: "/dept-json/", // url: "{% url 'accounts:dept-json'%}", success: function(response){ console.log(response) }, error: function(error){ console.log(error) } }) urls.py path('dept-json/', get_json_dept_data, name='dept-json'), path('prog-json/<str:department>/', get_json_prog_data, name='prog-json'), views.py def get_json_dept_data(request): qs_val = list(Department.objects.values()) return JsonResponse({'data':qs_val}) def get_json_prog_data(request, *args, **kwargs): selected_department = kwargs.get('department') obj_prog = list(Program.objects.filter(department__name=selected_department).values()) return JsonResponse({'data':obj_prog}) -
I already have a form created in HTML, how can I post the data from this form to the user's account on the Django database?
I am working on the project in which one user can create a quiz on the HTML pages without coding, in an interactive way. This created quiz should be displayed on the screen of another user, who will be attempting the tests. I am using Django framework for backend and I am very new to backend. -
Djangi : django.core.exceptions.FieldError: Cannot resolve keyword 'email' into field
**I Got errors like that, please help me. django.core.exceptions.FieldError: Cannot resolve keyword 'email' into field. Choices are: auth_token, created_at, id, is_verified, nama, order, pengiriman, user, user_id view.py def processOrder(request): id_transaksi = datetime.datetime.now().timestamp() data = json.loads(request.body) if request.user.is_authenticated: customer = request.user.profile order, created = Order.objects.get_or_create(user=customer, selesai=False) else: customer, order = gusetOrder(request, data) total = float(data['form']['total']) order.id_transaksi = id_transaksi if total == order.get_cart_total: order.selesai = True order.save() if order.shipping == True: Pengiriman.objects.create( user=customer, order=order, alamat=data['shipping']['address'], kota =data['shipping']['city'], provinsi=data['shipping']['state'], kode=data['shipping']['zipcode'], ) return JsonResponse('Payment complete', safe=False) checkout.html function submitFormData(){ console.log('Payment button clicked') var userFormData = { 'name':null, 'email':null, 'total':total, } var shippingInfo = { 'address':null, 'city':null, 'state':null, 'zipcode':null, } if (shipping != 'False'){ shippingInfo.address = form.address.value shippingInfo.city = form.city.value shippingInfo.state = form.state.value shippingInfo.zipcode = form.zipcode.value } if (userau == 'False'){ userFormData.name = form.name.value userFormData.email = form.email.value } console.log('Shipping Info:', shippingInfo) console.log('User Info:', userFormData) var url = "/process_Order" fetch(url, { method:'POST', headers:{ 'Content-Type':'applicaiton/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'form':userFormData, 'shipping':shippingInfo}), }) .then((response) => response.json()) .then((data) => { console.log('Success:', data); alert('Transaction completed'); cart = {} document.cookie ='cart=' + JSON.stringify(cart) + ";domain=;path=/" window.location.href = "{% url 'store' %}" }) } base.html function getToken(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for … -
Relation between two models in Django
It seems like a trivial question but I am new to Django. I have two models user and competition. The user can create and join one or many competition. How to specify this relation as the user can be the owner of competition/s and can be a participant in one or more competition. -
data encryption on amazon Aurora and django system
I am using amazon aurora and django. Now, thinking about using RDS encryption Hoever while reading documents, a few questions come up to me. My final goal is encrypting data itself, even mysql root user can not check the data. This doesn't encrypt the database data itself, so if DB user/password is leaked, the data could be stolen? Is there any good way to encrypt the data in database? even root mysql user can not check the data. I am using django, It is enough that only django can encode-decode the data. I should use some django library not database itself? or database has some structure for this purpose? -
Django still working fine even when DEBUG=False in settings.py
In settings.py, DEBUG set to True. But when we move it to the production we should be setting DEBUG=False. So in my local environment itself, I have changed to DEBUG=False. But still my application is working fine even with this settings. Usually when we changed DEBUG to false we should be getting some issues like 500 or 404 error something like that , but in my case its not like that. I have referred this """ https://stackoverflow.com/questions/38617046/django-debug-false-still-runs-in-debug-mode/47266619""" but it did not help much for me. Please let me know if i misunderstood or missed something. Below is the small snippet of code i have in settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]' DEBUG = False ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'MyApp', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] 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', ] Please let me know if i need to provide anymore details. -
DJANGO : checkout:293 POST http://127.0.0.1:8000/process_Order 403 (Forbidden)
```Help errorrrhi [enter image description here][1]I got error like that please help me[ def processOrder(request): id_transaksi = datetime.datetime.now().timestamp() data = json.loads(request.body) if request.user.is_authenticated: customer = request.user.profile order, created = Order.objects.get_or_create(user=customer, selesai=False) else: customer, order = gusetOrder(request, data) total = float(data['form']['total']) order.id_transaksi = id_transaksi if total == order.get_cart_total: order.selesai = True order.save() if order.shipping == True: Pengiriman.objects.create( user=customer, order=order, alamat=data['shipping']['address'], kota =data['shipping']['city'], provinsi=data['shipping']['state'], kode=data['shipping']['zipcode'], ) return JsonResponse('Payment complete', safe=False) function submitFormData(){ console.log('Payment button clicked') var userFormData = { 'name':null, 'email':null, 'total':total, } var shippingInfo = { 'address':null, 'city':null, 'state':null, 'zipcode':null, } if (shipping != 'False'){ shippingInfo.address = form.address.value shippingInfo.city = form.city.value shippingInfo.state = form.state.value shippingInfo.zipcode = form.zipcode.value } if (userau == 'False'){ userFormData.name = form.name.value userFormData.email = form.email.value } console.log('Shipping Info:', shippingInfo) console.log('User Info:', userFormData) var url = "/process_Order" fetch(url, { method:'POST', headers:{ 'Content-Type':'applicaiton/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'form':userFormData, 'shipping':shippingInfo}), }) .then((response) => response.json()) .then((data) => { console.log('Success:', data); alert('Transaction completed'); cart = {} document.cookie ='cart=' + JSON.stringify(cart) + ";domain=;path=/" window.location.href = "{% url 'store' %}" }) } function getToken(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this … -
Can I access Django Admin Site using deployed URL?
I just deploy my first Django Rest Framework into Heroku. Site URL is https://mysite.herokuapp.com/ I already can access admin site using http://127.0.0.1:8000/ through created superuser account. But How I am gonna access the admin site using the deployed url?. Thanks -
Django Migrations with multiple legacy databases with multiple tables in same app
Need help with migrations of already existing databases (MySQL) with lots of tables and data. These databases were manually being updated from CLI but now they need a web interface with all the stats and collaborations etc. The tables are connected between DBs and let's say there are 10tables in db1, 5 tables in db2. I have two apps 'login' and 'main'. Login: The 'default' database is being used for authentication/login. model.py is in app 'login'. Db setting for 'default' is in settings.py This is working fine. Initial migrations worked. Main: Second app, 'main', is suppose to connect to two databases, db1, db2 and fetch/update/remove data to already existing data through views. I added the mysql connector to settings.py with database parameters and it's able to connect via dbshell. Connection is working. Using 'inspectdb' I got the two models, one from each database (m1.py, m2.py). The 'models.py' in main app is empty for now. 'managed' in meta is False for all classes generated via inspectdb. Q: How to put all the tables/classes from both the databases (m1, m2) into models.py and do migrations? If I do migrate it can affect the 'default' (please correct me). If I specify the --database … -
Python/Docker - Method delete not allowed Django
I am trying to run a program using docker that will allow me to destroy requests by using a program called PostMan to do this I have set up a class named ProductViewSet which will allow me to delete a query. But when I run docker-compose up in my Visual Studio Terminal and try to run a DELETE query through PostMan it gives me an error in PostMan that says "detail": method "DELETE" not allowed. I have tried to use the @action function to try and link the destroy function from my views.py to my urls.py in the same folder using this answer Method Delete Not Allowed - destroy() method Django, I have also tried to just use my main function Product and use a router as seen in this answer "detail": "method \delete\ not allowed" django but both of these answers do not help me at all. Here is my error that I am getting in PostMan and in my Visual Studio Terminal: Postman: { "detail": "Method \"DELETE\" not allowed." } Visual Studio Terminal: backend_1 | 172.19.0.1 - - [16/Mar/2022 00:58:14] "DELETE /api/products HTTP/1.1" 405 - Here are my requirements.txt, Dockerfile, docker-compose.yml, and views.py files respectivly: requirements.txt: Django==3.1.3 djangorestframework==3.12.2 … -
Delete db.sqlite via terminal (Django)
I'm currently deploying a project to Heroku, however it returns me the following error: ValueError: Related model 'store.user' cannot be resolved. But there is a way to avoid such error locally. You simply do: py manage.py migrate store And then py manage.py migrate In other words, if I migrate separetely, I won't face such error. However, Heroku migrates all together, then the deploy fails because of this error. If I proceed locally as Heroku does, i.e. run py manage.py migrate I can effortlessly click on and delete the db.sqlite3 file and makemigrations and migrate separetely. Then the issue would be resolved. However, that's not possible when deploying to Heroku. Thus, how can I delete this file only via terminal? I have been searching, but people only say you click on the file and the delete it, which for me it is not possible. Thanks -
How to add source code option to Rick text field in django
I want to add the source code functionality to my rich text field in Django and I don't know how to go about it. I already know how to install and setup rich text field but how to add the source code functionality is what I need -
Call html file in iframe with javascript, in a django project
I want to open a html file of a Django application, in a javascript. document.getElementById("iframe_id").src = "{% url 'application/file.html' %}"; I receive the error : Exception Type: NoReverseMatch Exception Value: Reverse for 'application/file.html' not found. 'application/file.html' is not a valid view function or pattern name. -
DRF DefaultRouter pk/slug
I noticed that sites such as SO and Reddit use <basename>/<pk>/<slug>/ for the detail view of posts, which makes me think that this should be the standard. Is there a way to accomplish this in drf using routers and ModelViewset? example of ModelViewset: class PostViewSet(viewsets.ModelViewSet): ... lookup_fields = ['pk', 'slug'] example of DefaultRouter : router = DefaultRouter() router.register('posts', PostViewSet, basename='post') app_name = 'api' urlpatterns = [ path('', include(router.urls)), ] URL patterns: /api/post/ api.views.PostViewSet post-list /api/post/<pk>/<slug>/ api.views.PostViewSet api:post-detail /api/post/<pk>/<slug>\.<format>/ api.views.PostViewSet api:post-detail /api/post\.<format>/ api.views.PostViewSet api:post-list -
Authentication credentials weere not provided when signing up
Building Django APIs to help me handle both the signup and login process for my React app. I am able to successfully login (get an access and refresh token from Django upon login), but having difficulties connecting my React signup process to Django to create a new user. This is the error I am getting on my console: POST http://127.0.0.1:8000/users/ 401 (Unauthorized) onSubmit @ Signup.js:32 and on my network: Authentication credentials were not provided. This is what I have in my serializers.py from django.contrib.auth.models import User from rest_framework import serializers class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'email', 'password'] extra_kwargs = { 'password': {'write_only':True}, } def create(self,validated_data): user = User.objects.create_user(validated_data['username'], password=validated_data['password'], email=validated_data['email']) return user class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' class UserSerializerWithToken(serializers.ModelSerializer): token = serializers.SerializerMethodField() password = serializers.CharField(write_only=True) class PasswordSerializer(serializers.Serializer): old_password = serializers.CharField(required=True) new_password = serializers.CharField(required=True) accounts.urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('signup.urls')), ] signup.urls.py from django.contrib import admin from django.urls import path, include from rest_framework import routers from . import views from rest_framework_simplejwt.views import (TokenObtainPairView, TokenRefreshView, TokenVerifyView) from .api import RegisterApi router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) urlpatterns = [ path('', include(router.urls)), path('admin/', … -
Posting images to userProfile django
I was able to automaticcaly create a userProfile everytime a user is created but I want to be able to modify somefields in the userprofile. So my Model.py def upload_path(instance,filename): return 'users/avatars/{0}/{1}'.format(instance.user.username, filename) class UserProfile(models.Model): user= models.OneToOneField(User,on_delete=models.CASCADE, related_name='userprofile') Profileimage= models.ImageField(upload_to=upload_path, blank=True, null=True, default='user/avatar.jpeg') def __str__(self): return self.user.username @ receiver(post_save,sender=User) def create_user_profile(sender,instance,created,**kwargs): if created: UserProfile.objects.create(user=instance) My Serializer.py class UserSerializer(serializers.ModelSerializer): #ProfileImage=serializers.ImageField(allow_null=True, use_url=True) class Meta: model = User fields =['id', 'username','password','email'] extra_kwargs={'password':{'write_only':True, 'required':True}} def create(self,validated_data): user =User.objects.create_user(**validated_data) Token.objects.create(user=user) return user class UserProfileSerializer(serializers.ModelSerializer): user = serializers.StringRelatedField(read_only=True) class Meta: model =models.UserProfile #lookup_field = 'username' fields= ['id','user','Profileimage'] My view.py class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer lookup_field = 'username' class UserProfileViewSet(viewsets.ModelViewSet): queryset = UserProfile.objects.all() serializer_class = UserProfileSerializer lookup_field = "username" The page looks like : enter image description here So how can I modify the picture of the user, I tried to add forms but I couldn't match the username, sometime I guet the error Userprofile has no user. Anyhelp? -
Django no such table: Fligts_country when trying to migrate app model using Foreign key
Intro Hi, first off thanks in advanced for helping. I am learning the Django framework and I am having trouble trying to create a simple relation between two tables in my model. I am running django and mysql in docker in two separate containers, created by a docker-compose file (code is down below) and so far I have not been able to create the tables (migrations). Problem When I execute the command: python manage.py migrate --database=mariadb I get as a result: django.db.utils.OperationalError: no such table: Fligts_country In other posts similar to this one (Django - no such table exception for example) I see that a common solution is to remove the pycache folder and migrations as well, but this is not working for me and I have been strugling for some time now... Desired Solution I need the tables to be created in the database, but most importantly I want to know what is exactly wrong with my code. I assume that there is something that I am missing about Foreign keys. My code so far Docker-compose.yml version: '3' services: travel-crawler: restart: always container_name : travel-crawler build: ./Crawler tty: true ports: - '9005:8080' volumes: - type: bind source : E:\python-code\Traveler\Crawler …