Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is my Python Django home url not working?
my first url in django is not working. Not sure what I am doing. My directories are as follows: Storefront playground urls.py views.py storefront urls.py playground.urls from nturl2path import url2pathname from django.urls import path from . import views urlpatterns = [ path('hello/', views.hello) ] playground.views from django.shortcuts import render from django.http import HttpResponse def hello(request): return HttpResponse('Hello World') storefront.urls from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('playground/', include('playground.urls')) ] When I go to the website/playground/url, I get an error saying the urls wasn't found. What am I doing wrong? -
Django model queryset order objects in the same order as how they appear in filter_horizontal box
I am having trouble in figuring out how to query for objects in Django model, so that the queried results are exactly as how objects appear in the selected filter list. Let me explain this more clearer. We assume I have two models, one called TakeawayWebshop and one called Product. A TakeawayWebshop can sell many products, but when the customer views the product page, I want the product to appear in the order that I have included them in the filter box. In models.py class TakeawayWebshop(models.Model): name = models.CharField(max_length = 255, help_text = 'name of takeaway restaurant') products = models.ManyToManyField(Product) class Product(models.Model): name = models.CharField(max_length = 50, unique=True) description = models.TextField() price = models.DecimalField(max_digits=9, decimal_places=0, default=0.00) class Meta: ordering = ['-created_at'] In the admin.py I have added product in filter_horizontal. Is it possible to obtain a query set of product that is added to the TakeawayWebshop in the same order as how they appear in the filter_horizontal? Also currently, it is not possible to move the product up or down in the filter_horizontal box from admin. Is there a clever way to implement this feature? class TakeawayWebshopAdmin(admin.ModelAdmin): form = TakeawayWebshopAdminForm list_display = ['name'] ordering = ['name'] filter_horizontal = ('products',) admin.site.register(TakeawayWebshop, … -
Retrieving selected fields from a Foreign Key value with django-rest-framework serializers. (how to get some of the fields of the ForeignKey.)
My Model Class for the artist, album, and track. class Artist(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField() class Album(models.Model): album_name = models.CharField(max_length=100) artist = models.ForeignKey(Artist, related_name='albums', on_delete=models.CASCADE) class Track(models.Model): album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE) title = models.CharField(max_length=100) duration = models.IntegerField() My serializer for the respective models. class ArtistSerializer(serializers.ModelSerializer): class Meta: model = Artist fields = '__all__' class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = ['title', 'duration'] class AlbumSerializer(serializers.ModelSerializer): tracks = TrackSerializer(many=True, read_only=True) class Meta: model = Album fields = '__all__' depth = 1 For retrieve, The output is as {'id': 1, 'tracks': [{'title': 'Public Service Announcement', 'duration': 245}, {'title': 'What More Can I Say', 'duration': 264}], 'album_name': 'The Grey Album', 'artist': {'id': 1, 'first_name': 'lala', 'last_name': 'nakara','email':'lalanakara@yahoo.com'} } My desired output: I want to get rid of the email field. I looked at the Django-rest-framework documentation, but could not find anything related to the selective field from foreign keys. {'id': 1, 'tracks': [{'title': 'Public Service Announcement', 'duration': 245}, {'title': 'What More Can I Say', 'duration': 264}], 'album_name': 'The Grey Album', 'artist': {'id': 1, 'first_name': 'lala', 'last_name': 'nakara'} } -
How to pass error message for custom permission in Django Rest Framework?
I have a custom permission and it called IsVendor. Now I have two built in permission class and they are IsAdminUser, IsAuthenticated and when I try to hit those url without credentials or login information it shows me an error message like this one 'details':'Authentication Credentials are not provided' and I want the same for my custom permission error message. But it is showing Anonymoususer has no object vendor. class IsVendor(BasePermission): def has_permission(self, request, view): if request.user.vendor: return True else: return False this is my custom permission class. I want to pass error message like 'Authentication Credentials not provided' -
Celery makes print() not visibile
(portfolio) PS C:\Users\arund\Desktop\Code\Django\portfolio-project> celery -A portfolio beat -l info celery beat v5.2.3 (dawn-chorus) is starting. __ - ... __ - _ LocalTime -> 2022-03-19 14:41:16 Configuration -> . broker -> redis://:**@-// . loader -> celery.loaders.app.AppLoader . scheduler -> celery.beat.PersistentScheduler . db -> celerybeat-schedule . logfile -> [stderr]@%INFO . maxinterval -> 5.00 minutes (300s) [2022-03-19 14:41:16,221: INFO/MainProcess] beat: Starting... [2022-03-19 14:41:16,738: INFO/MainProcess] Scheduler: Sending due task print-message-once-and-then-every-minute (print_time) [2022-03-19 14:42:00,004: INFO/MainProcess] Scheduler: Sending due task print-message-once-and-then-every-minute (print_time) [2022-03-19 14:43:00,000: INFO/MainProcess] Scheduler: Sending due task print-message-once-and-then-every-minute (print_time) [2022-03-19 14:44:00,000: INFO/MainProcess] Scheduler: Sending due task print-message-once-and-then-every-minute (print_time) I am trying to setup a periodic task using celery but the print() function seems to not be visible even through it does run. Specifically in using the print_time in the tasks.py. tasks.py from celery import shared_task from datetime import datetime from __future__ import absolute_import, unicode_literals @shared_task(name = "print_time") def print_time(): now = datetime.now() current_time = now.strftime("%H:%M:%S") print("Current Time is ") celery.py from __future__ import absolute_import import os from celery import Celery from django.conf import settings from decouple import config from celery.schedules import crontab # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'portfolio.settings') app = Celery('portfolio') app.conf.update(BROKER_URL=config('REDIS_URL'), CELERY_RESULT_BACKEND=config('REDIS_URL')) # Using a string … -
Django Q objects in model constraints
I am trying to extend a model in an Django App. The only problem I have is that I need to extend the model constraints as well and that does not work properly. This is the original constraint for the object in models.py: models.CheckConstraint( check=( models.Q(inventory_item__isnull=True, device_type__isnull=False) | models.Q(inventory_item__isnull=False, device_type__isnull=True) ), name="At least one of InventoryItem or DeviceType specified.", ) I have tried to extend it like that: models.CheckConstraint( check=( models.Q(inventory_item__isnull=True, device_type__isnull=False, module_type__isnull=False) | models.Q(inventory_item__isnull=False, device_type__isnull=True, module_type__isnull=False) | models.Q(inventory_item__isnull=False, device_type__isnull=False, module_type__isnull=True) ), name="At least one of InventoryItem, ModuleType or DeviceType specified.", ), This is how this looks in the migration: migrations.AddConstraint( model_name='hardwarelcm', constraint=models.CheckConstraint(check=models.Q(models.Q(('device_type__isnull', False), ('inventory_item__isnull', True), ('module_type__isnull', False)), models.Q(('device_type__isnull', True), ('inventory_item__isnull', False), ('module_type__isnull', False)), models.Q(('device_type__isnull', False), ('inventory_item__isnull', False), ('module_type__isnull', True)), _connector='OR'), name='At least one of InventoryItem or ModelType or DeviceType specified.'), ) My problem is that I tried all combinations and it fails every time, but I can see from the error message that only one value is set and the other are Null. DETAIL: Failling row contains (3, null, 1, null) Is there some limitation with Q objects that I don't understand? I have tried to read the Django documentation, but could not figure out what the problem is. -
How to design object model to show them like rectangular cards and add student in a class for a online clasroom project in django
I am doing an online classroom project like google classroom. So I created a model for teachers to add courses now if a teacher adds 2-3 or more courses how will I show all of his created courses on his homepage like rectangular cards we see on google classroom also how I add a student to that class I created a unique "classroom_id" field in course model how I will design that student can join that particular class by entering the classroom id. models.py from django.db import models Create your models here from jazzmin.templatetags.jazzmin import User class course(models.Model): course_name = models.CharField(max_length=200) course_id = models.CharField(max_length=10) course_sec = models.IntegerField() classroom_id = models.CharField(max_length=50,unique=True) created_by = models.ForeignKey(User,on_delete=models.CASCADE) views.py def teacher_view(request, *args, **kwargs): form = add_course(request.POST or None) context = {} if form.is_valid(): course = form.save(commit=False) course.created_by = request.user course.save() return HttpResponse("Class Created Sucessfully") context['add_courses'] = form return render(request, 'teacherview.html', context) -
Django mongodb annotate ExtractDay/Month
I'm not using ExtractDay, ExtractHour etc. in mongodb based Django. Example views.py code: data.filter(find_date__year=2022).annotate(day=ExtractDay('date')) Error status :) : No exception message supplied -
How to use django shell in multiple databases
I am trying to run django shell in different databases. But without success. What I have tried it's override the django Command, and setup my own connection. Take a look on the example bellow. But it's seems like not working solution. Any thoughts how to do that ? Unfortunately the solution with Model.objects.using("db_name")..... not a good one for my case. Code which I have tried: class Command(DefaultShell): def add_arguments(self, parser): super().add_arguments(parser) parser.add_argument( '--database', dest='database_name', help='Specific database to run shell', required=False, ) def __set_database_for_current_connection(self, database_name: str): connections.ensure_defaults(database_name) connections.prepare_test_settings(database_name) db = connections.databases[database_name] backend = load_backend(db['ENGINE']) return backend.DatabaseWrapper(db, database_name) def handle(self, *args, **options): database = options.get('database') conn = self.__set_database_for_current_connection(database) super().handle(*args, **options) conn.close() -
Django - unused import statement
I'm a beginner to Django and currently undertaking the codeacademy 'build web apps with django course'. To help better understand django and python I decided to use Pycharm rather than the website interface. I've setup my project, ran the server, migrated and setup an app called 'randomfortune'. I'm now up to the step where I create a view function in views.py: def myview(request): return request, 'randomfortune/fortune.html' In urls.py I use the below imports but I get an error saying 'unused import statement'. from django.urls import path from . import views I done some searching previously and my venv does point to python.exe and it still doesnt work can anybody help out as I'm stuck to the point that I cant continue with the course. -
Increment id within a parent entity in Django model
I have this problem where I have a parent model User that is one-to-many linked to another model say Device. What I want to do is within each user, I want to create and increment an id for each device he own. Something like user A have two devices so his user_device_id will be 1 and 2. user B have one device so his user_device_id will be 1. vice versa. I have a current working solution but I am looking for an alternative solution. The Device model currently implemented which overrides save method: class Device(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) user_device_id = models.PositiveIntegerField(default=0, null=false) def save(self, *args, **kwargs): try: within_user_device_id = Device.objects.filter(user=self.user).latest('user_device_id').user_device_id self.user_device_id = within_user_device_id + 1 except Device.DoesNotExist: self.user_device_id = 1 For the neater method, in my mind, to create a function that gets the current instance of user and use the default in models.PositiveIntegerField to increment this value. The problem is I cannot get refer the current instance and call the function in default. class Device(models.Model): def increment_within_user_device_id(self): within_user_device_id = Device.objects.filter(user=self.user).latest('user_device_id').user_device_id if not within_user_device_id: return 1 else: within_user_device_id += 1 return within_user_device_id user = models.ForeignKey(User, on_delete=models.CASCADE) # I cannot pass the function in default user_device_id = models.PositiveIntegerField(default=increment_with_user_device_id(self), null=false) Any … -
Django: Old url is still searched after POST request
I am fairly new to Django and now at my wit's end with the following issue. I have changed the url name from 'odata' to 'database' and the app properly redirects to the url http://127.0.0.1:8000/database/. However while being at http://127.0.0.1:8000/database/ and making the POST request using ajax, the app freezes and on looking in the browser's developer tools I see the error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/odata/ . . . The current path, odata/, didn't match any of these. Why the old name is still being searched? I have made changes in the following files and codes: my_app/url.py urlpatterns = [ path('', views.view1, name = "view1"), path('database/', views.view2, name = "view2"), #old name was odata/ ] myreq.js function submit_training() { $.ajax({ url: '/database/', //earlier- /odata/ data: $('form#db_settings').serialize(), method: 'POST', ... } When I revert the changes to 'odata' everything works as expected. I am not sure what I am missing here. I apologize for not providing more or exact codes, as I am not supposed to disclose details on the project. However, I can still furnish more information, if required. Your time and help is much appreciated!! -
White blank page when I deploy my (React.js & Django) app to Heroku
I'm beginner and the project works perfectly locally , but when I deploy on Heroku I get a blank page. package.json (I tried adding "homepage": "." but it didn't work to me even after rebuild again ): { "name": "frontend", "homepage": "aroundtheword.herokuapp.com/", "version": "0.1.0", "private": true, "dependencies": { "@testing-library/jest-dom": "^5.16.2", "@testing-library/react": "^12.1.4", "@testing-library/user-event": "^13.5.0", "axios": "^0.26.1", "react": "^17.0.2", "react-dom": "^17.0.2", "react-router-dom": "^6.2.2", "react-scripts": "^5.0.0", "uuid": "^8.3.2", "web-vitals": "^2.1.4" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject", "postinstall": "npm run build" }, "eslintConfig": { "extends": [ "react-app", "react-app/jest" ] }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] }, "engines": { "node": "16.13.0", "npm": "8.1.0" } } index.html (public folder): <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel="icon" href="%PUBLIC_URL%/favicon.ico" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="theme-color" content="#000000" /> <meta name="description" content="Web site created using create-react-app" /> <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" /> <!-- manifest.json provides metadata used when your web app is installed on a user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/ --> <link rel="manifest" href="%PUBLIC_URL%/manifest.json" /> <!-- Notice the use of %PUBLIC_URL% in the … -
How to Redirect URLs Dynamically
Can someone guide me please how to approach this concept with .htaccess, HTML, JavaScript, Django and DB (I don't know whether database is necessary or not)? Concept Design -
Using Django For Loop in Drop Down Menu
I'm trying to iterate through a list of recommendations previously entered by the user and make each recommendation an item in a drop down list. Image of the Code I'm using Image of the Results I'm getting -
ValueError: Canot asign "<django.contrib.auth.models.AnonymousUser object at 0x..40>": "Members.user" must be a "User" instance. [2..7] "POST /api/
I'm trying to register a user and have the email part go into the user name from the Members model, but I'm getting the above error. kindly assist. In auth_user username Equals [blablabla]@gmail.. in brackets I'm trying to add the same to the Members user, for a ForeignKey relationship. To make user equal to blablabla Serializers class RegisterSerializer(serializers.ModelSerializer): password1 = serializers.CharField(required=True) password2 = serializers.CharField(required=True) user = serializers.HiddenField(default=serializers.CurrentUserDefault()) class Meta: model = Members fields = ('first_name', 'last_name', 'user', 'email', 'photo', 'gender', 'password1', 'password2') def validate_email(self, email): email = get_adapter().clean_email(email) if allauth_settings.UNIQUE_EMAIL: if email and email_address_exists(email): raise serializers.ValidationError("A user is already registered with this email address.") return email def validate_password1(self, password): return get_adapter().clean_password(password) def validate(self, data): if data['password1'] != data['password2']: raise serializers.ValidationError("The two password fields didn't match.") return data def get_cleaned_data(self): return { 'password1': self.validated_data.get('password1', ''), 'email': self.validated_data.get('email', ''), }, { 'first_name': self.validated_data.get('first_name', ''), 'last_name': self.validated_data.get('last_name', ''), 'photo': self.validated_data.get('photo', ''), 'gender': self.validated_data.get('gender', ''), 'email': self.validated_data.get('email', ''), 'user': self.validated_data.get('user', ''), } def save(self, request): adapter = get_adapter() user = adapter.new_user(request) self.cleaned_data, data_for_members = self.get_cleaned_data() Members.objects.create(**data_for_members) adapter.save_user(request, user, self) setup_user_email(request, user, []) user.save() return user class LoginSerializer(RestAuthLoginSerializer): username = None Models class Members(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) photo = models.ImageField(upload_to='photos/%Y/%m/%d/') gender_choices = (('F', … -
'QuerySet' object has no attribute 'comments'
while runnig http://127.0.0.1:8000/blogapp/blogdata/53/ i get error AttributeError at /blogapp/blogdata/53/ 'QuerySet' object has no attribute 'comments' and it says expected error location is views.py line 42 which is comments=blogmodel.comments.all() models.py class Blogmodel(models.Model): author=models.ForeignKey(User,on_delete=models.CASCADE,blank=True,null=True) title=models.CharField(max_length=200) Newpost=models.TextField(max_length=1000) summary=models.TextField(max_length=50,blank=True) created_date=models.DateTimeField(auto_now_add=True) published_date=models.DateTimeField(auto_now=True) def __str__(self): return f'{self.title},{self.Newpost},{self.published_date},{self.created_date}' class commentmodel(models.Model): blogmodel=models.ForeignKey(Blogmodel,related_name='comments' ,on_delete=models.CASCADE,blank=True,null=True) comment=models.CharField(max_length=200) active=models.BooleanField(default=True) def __str__(self): return f'{self.comment},{self.blogmodel.title}' views.py def blogretrieve(request): blogmodel=Blogmodel.objects.all().order_by('-published_date') context={'blogmodel':blogmodel,} return render(request,'blogapp/blogretrieve.html',context) def blog(request,pk): blogmodel=Blogmodel.objects.filter(id=pk) #comments = y.comments.filter(active=True) comments=blogmodel.comments.all() #line 42 context={'blogmodel':blogmodel,'comments':comments} return render(request,'blogapp/blogpk.html',context) urls.py app_name='blogapp' urlpatterns=[ path('',views.home,name='home'), path('createblog/',views.blogview,name='blogview'), path('blog/',views.blogretrieve,name='blog'), path('signup/',views.signupview,name='signup'), path('login/',views.loginview,name='login'), path('logout/',views.logoutview,name='logout'), path('author/<str:pk>/',views.authorview,name='author'), path('blogdata/<str:pk>/',views.blog,name='blogdata'), -
DjangoRestFramework: Assign CustomUser failed
Good evening, inside my djano-application I've created a custom user... class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email ...and added the following code snippet into settings.py: AUTH_USER_MODEL = 'app_something.CustomUser' My Question: how can I add it into the following - let's say - put request: ... elif request.method == 'PUT': serializer = SomethingSerializer(qs, data=request.data) if serializer.is_valid(): serializer.save(user_created=request.user) # --> line that causes the error return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) ... Right now I'm trying to add the request.user, which fails with the error something_user_created" must be a "CustomUser" instance. My first idea was to add the CustomUser like this, but I dont't know how to get the active user inside my view: from app_something.models import CustomUser customuser = CustomUser.objects.get(id=???) ... serializer.save(user_created=customuser) ... Does anyone know what I'm doing wrong here? Thanks for you help and have a great day! -
error code H10 while deploying django app on heroku
hi i am trying to deploy my django app to heroku but it gives me this error: ** note " the build was successful " enter image description here this is another photo: enter image description here the error code: 2022-03-20T17:01:35.874001+00:00 heroku[router]: at=error code=H13 desc="Connection closed without response" method=GET path="/" host=beta-stega.herokuapp.com request_id=37d48eef-1019-4eb1-93a5-50d4c8db7f6b fwd="46.248.201.72" dyno=web.1 connect=8ms service=634ms status=503 bytes=0 protocol=https 2022-03-20T17:01:35.874312+00:00 heroku[router]: at=error code=H13 desc="Connection closed without response" method=GET path="/" host=beta-stega.herokuapp.com request_id=7054bc05-06f4-43c5-bdea-8b49a610054d fwd="46.248.201.72" dyno=web.1 connect=0ms service=236ms status=503 bytes=0 another error code (i think that): 2022-03-20T17:01:49.757829+00:00 heroku[router]: at=error code=H13 desc="Connection closed without response" method=GET path="/favicon.ico" host=beta-stega.herokuapp.com request_id=dbe2cac6-8715-4525-a05a-0c88bb3c8815 fwd="46.248.201.72" dyno=web.1 connect=5000ms service=53ms status=503 bytes=0 protocol=https 2022-03-20T17:02:04.006106+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=beta-stega.herokuapp.com request_id=ae1a7cae-51b4-461b-9ce6-b83b4966e78a fwd="46.248.201.72" dyno= connect= service= status=503 bytes= protocol=https 2022-03-20T17:02:04.577385+00:00 heroku[router]: at=error w desc="App crashed" method=GET path="/favicon.ico" host=beta-stega.herokuapp.com request_id=e00b7566-3ccb-4a04-bdf5-8b814e6874bb fwd="46.248.201.72" dyno= connect= service= status=503 bytes= protocol=https website error image : enter image description here build log image : enter image description here ** note " the work fine on local host " can anyone help :) -
/opt/alt/python39/bin/lswsgi: No such file or directory
I have a shared Cpanel host with Litespeed web server. I want to deploy a django application on it. After creating Python application inside the Cpanel where I have not deployed the application on the host I try loading the web site, and instead of displaying django version I face 503 Unavailable!! Also inside the "stderr.log" file there is following error. /usr/local/lsws/fcgi-bin/lswsgi_wrapper: line 9: /opt/alt/python39/bin/lswsgi: No such file or directory -
how to fetch data from a list of dictionary using django
I am trying to develop a dictionary(using django) that contains a voice for pronunciation. everything goes fine but I cannot relate the audio with the word using the following query. Model.py class Warehouse(models.Model): word = models.CharField(max_length=200, blank=True) type = models.CharField(max_length=200, blank=True) gender = models.CharField(max_length=200, blank=True) meaning = models.TextField(max_length=2000, blank=True) synonyms = models.CharField(max_length=200, blank=True) antonyms = models.CharField(max_length=200, blank=True) usage = models.TextField(max_length=2000, blank=True) class Audio(models.Model): warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE) audio_file = models.FileField(upload_to='audio') def __str__(self): return self.warehouse.word def delete_media(self): os.remove(path=MEDIA_ROOT + '/' + str(self.audio_file)) query.py def get_words_warehouse_matching(search_sting): try: dictionary_object = Warehouse.objects.filter(Q(word__icontains = search_sting)|Q(type__icontains=search_sting) | Q(gender__icontains=search_sting)|Q(synonyms__icontains=search_sting)|Q(antonyms__icontains=search_sting) words_list = [] for words in dictionary_object.iterator(): word_dictionary = {'id':words.id, 'word': words.word, 'meaning': words.meaning, 'synonyms': words.synonyms,'antonyms': words.antonyms} words_list.append(word_dictionary) return words_list views.py def search(request): context = {} warehouse={} if request.method == 'POST': context['data'] = get_words_by_matching(request.POST['searchString']) context['warehouse'] = get_words_warehouse_matching(request.POST['searchString']) voice = Audio.objects.filter(warehouse_id = warehouse.id) context['audio'] = voice return render(request, 'dictionary/word.html', context) I need to display the related audio file in the template so that I need to equate warehouse_id to Warehouse.id. How can I fetch the id from get_words_warehouse_matching (dictionary) so that I could use filter(warehouse_id = warehouse.id) in views. Or if there are any other better options, suggestions would be highly appreciated. Thanks in advance. -
No module named '_tkinter : on deploying to heroku
Am trying to deploy a Django React application on heroku but get error ModuleNotFoundError: No module named '_tkinter'. The application is running absolutely fine in local. But, after deploying in Heroku, I am getting the below error. remote: Traceback (most recent call last): remote: File "/app/manage.py", line 22, in <module> remote: main() remote: File "/app/manage.py", line 18, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute remote: django.setup() remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/__init__.py", line 24, in setup remote: apps.populate(settings.INSTALLED_APPS) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/apps/registry.py", line 114, in populate remote: app_config.import_models() remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/apps/config.py", line 300, in import_models remote: self.models_module = import_module(models_module_name) remote: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module remote: return _bootstrap._gcd_import(name[level:], package, level) remote: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import remote: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load remote: File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked remote: File "<frozen importlib._bootstrap>", line 680, in _load_unlocked remote: File "<frozen importlib._bootstrap_external>", line 850, in exec_module remote: File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed remote: File "/app/portfolioApi/models.py", line 1, in <module> remote: from turtle import title remote: File "/app/.heroku/python/lib/python3.9/turtle.py", line 107, in <module> remote: import tkinter as TK remote: File "/app/.heroku/python/lib/python3.9/tkinter/__init__.py", line 37, in <module> remote: … -
How to track which user is creating object for a model and how to show the object details only to that user in django
I am doing an online classroom project in Django where I created a model named create_course which is accessible by teachers. Now I am trying to design this as the teacher who creates a class only he can see this after login another teacher shouldn't see his classes and how to add students into that particular class I created the course model class course(models.Model): course_name = models.CharField(max_length=200) course_id = models.CharField(max_length=10) course_sec = models.IntegerField() classroom_id = models.CharField(max_length=50,unique=True) created_by = models.ForeignKey(User,on_delete=models.CASCADE) here if I use "the created_by" field in forms it appears to be a drop-down menu where every user is showing but I want to automatically save the user who creates the object views.py def teacher_view(request, *args, **kwargs): form = add_course(request.POST or None) context = {} if form.is_valid(): form.save() return HttpResponse("Class Created Sucessfully") context['add_courses'] = form return render(request, 'teacherview.html', context) forms.py from django import forms from .models import course class add_course(forms.ModelForm): class Meta: model = course fields = ('course_name', 'course_id', 'course_sec', 'classroom_id') -
Hello, I want to send the information of a JSON to different databases, the json that I must receive has the following format(Python, Django) [closed]
{ "Table 1": { "field1":"...", "field2":"..." }, "table2": { "field1":"...", "field2":"..." } } -
Can i styling django login views?
I trying using django login views form django.contrib.auth.views, but I'm confused while trying to style it, is there any solution for that? from django.contrib.auth import views as auth_views path('accounts/login/', auth_views.LoginView.as_view()),