Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting type error when passing model in select tag in Django
I have a model called Department it has data College and HS, when I try to save my form I always get a TypeError. I've tried to validate the form and found out that it was an unbound form so I tried changing the Field type of department from ChoiceField to CharField and in my templates I tried calling {{form.department}} and it gives me the correct data yet it still gives TypeError. views.py class editProfile(UpdateView): model = Profile form_class = UpdateUserForm template_name = 'accounts/profile.html' success_url = reverse_lazy('homepage') #TypeError or ValueError def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['initial']=Profile.objects.get(user=self.request.user) context['department']=Department.objects.all() context['program']=Program.objects.all() context['year']=Year.objects.all() return context def form_valid(self, form): user = form.save(commit=False) user.username = form.cleaned_data.get('username') user.profile.department = form.cleaned_data.get('department') user.profile.program = form.cleaned_data.get('program') user.profile.year = form.cleaned_data.get('year') user.profile.save() user.save() forms.py class UpdateUserForm(forms.ModelForm): def __init__(self, *args, **kwargs) -> None: super(UpdateUserForm, self).__init__(*args, **kwargs) self.fields['username'].label = 'Username' self.fields['department'].label = 'Department' self.fields['program'].label = 'Program' self.fields['year'].label = 'Year' username = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Type your username' })) department = forms.CharField(widget=Select(attrs={ 'class': 'form-control' })) program = forms.CharField(widget=Select(attrs={ 'class': 'form-control', }, )) year = forms.CharField(widget=Select(attrs={ 'class': 'form-control', }, )) class Meta: model = User fields = ['department', 'program', 'year', 'username'] models.py class Department(models.Model): department=[ ('HS','Highschool Department'), ('College','College Department') ] name = models.CharField(_('Department'),max_length=50,choices=department) def … -
Django form creator
I am building a Django project which let users(teachers) create Forms for their students. they can add inputs and also options (for dropdown inputs). I solve this challenge by using dictionaries (I store their inputs and options in dictionaries and if they add options elements will be added to their keys as lists) I don't like the way that I am storing data (as dictionaries) in my database. I want to know if there are any features in Django that can let me produce module fields for my database. in short- I want to handle the database (create new fields) in my view. -
Iterate through non-queryset dictionary in a template
I have a dictionary that I am feeding into a chart.js line chart. It looks as follows: context['graph_data'] = {'day': [datetime.date(2022, 2, 28), datetime.date(2022, 3, 1), datetime.date(2022, 3, 2), datetime.date(2022, 3, 3), datetime.date(2022, 3, 4), datetime.date(2022, 3, 5), datetime.date(2022, 3, 6), datetime.date(2022, 3, 7), datetime.date(2022, 3, 8), datetime.date(2022, 3, 9), datetime.date(2022, 3, 10), datetime.date(2022, 3, 11), datetime.date(2022, 3, 12), datetime.date(2022, 3, 13), datetime.date(2022, 3, 14), datetime.date(2022, 3, 15), datetime.date(2022, 3, 16), datetime.date(2022, 3, 17), datetime.date(2022, 3, 18), datetime.date(2022, 3, 19)], 'response_totals': [0, 0, 0, 0, 12, 12, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]} The template section that I am getting tripped up on looks like the following: new Chart(ctx1, { type: "line", data: { labels: [{%for i in graph_data%}{{i.day}},{%endfor%}], datasets: [{ label: "Referrals", tension: 0.4, borderWidth: 0, pointRadius: 2, pointBackgroundColor: "#cb0c9f", borderColor: "#cb0c9f", borderWidth: 3, backgroundColor: gradientStroke1, data: [{%for j in graph_data%}{{j.response_totals}},{%endfor%}], maxBarThickness: 6 }, I am a bit of a newbie. I can handle querysets but I'm not sure how to transform non-qs dictionaries via the template. -
ModuleNotFoundError: No module named 'commerce.wsgi' Heroku
I'm trying to deploy my django application to Heroku using github (downloaded zip file) but receiving this error ModuleNotFoundError: No module named 'commerce.wsgi'. I've made some edits with previous stackoverflow responses to questions like this but having same error. Django Wsgi ModuleNotFoundError: No module named 'project_name' HEROKU PAGE Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail WSGI.PY """ WSGI config for commerce project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ """ import os import sys sys.path.append('/home/django_projects/commerce') sys.path.append('/home/django_projects/commerce/commerce') from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'commerce.settings') application = get_wsgi_application() PROCFILE web: gunicorn commerce.wsgi HEROKU LOG TAIL 2022-03-20T22:12:10.677933+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 58, in load 2022-03-20T22:12:10.677933+00:00 app[web.1]: return self.load_wsgiapp() 2022-03-20T22:12:10.677933+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp 2022-03-20T22:12:10.677933+00:00 app[web.1]: return util.import_app(self.app_uri) 2022-03-20T22:12:10.677934+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/util.py", line 359, in import_app 2022-03-20T22:12:10.677934+00:00 app[web.1]: mod = importlib.import_module(module) 2022-03-20T22:12:10.677935+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module 2022-03-20T22:12:10.677935+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2022-03-20T22:12:10.677935+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import 2022-03-20T22:12:10.677935+00:00 app[web.1]: File … -
Running Django management commands in Visual Studio with .env file environment variables
I need to remove all sensitive keys from the code in my Django app, even those keys that are just used for local testing. The Visual Studio debugger can load environment variables from a .env file. I followed the official tutorial and it's worked, the dev server runs and my Django app can access environment values that are stored in the .env file. But I've hit an issue when I run custom Django management comments. Is there a way to run the commands from the debugger so that they can also access the environment variables? Or some other way to run the commands so they can access the key-value pairs in the .env file? -
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