Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django include template tag include multiple context object
I`m building a blog template page, which will include the Post list context object and the Category list context object. I`m using class-based view in the views.py: class CatListView(ListView): model = Category context_object_name = 'categories' template_name = 'blog/category.html' class PostListView(ListView): model = Post context_object_name = 'post_list' template_name = 'blog/blog.html' urls.py: urlpatterns = [ path('', views.PostListView.as_view(), name='blog'), ... ] using the include tag to include the category template in blog.html: {% extends 'base.html'%} {% block content %} <main class="main-content"> <div class="container mt-8"> <div class="row"> <div class="col-lg-8"> <h2>Post list</h2> {% for post in post_list %} {{ post.title }} {% endfor %} </div> <div class="col-lg-4"> {% include "blog/category.html"%} </div> </div> </div> </main> {% endblock %} category.html: <ul class="mt-8"> {% for cat in categories %} <li>{{ cat.title }}</li> {% endfor %} </ul> I just cant pass the category context in the post.html template. maybe Im can do it with the function-based view, but is it possible to pass multiple contexts into one template using only a class-based view? -
Django ReactJS - Exposing multiple graphql endpoints
I am building a web app using Django backend and ReactJS frontend. This web app will be a culmination of several smaller applications like Todo app, Investments Tracker, Budget Analysis etc. Frontend: This I how I have structured the frontend (ReactJS project): src - apps - Home - index.jsx - Todo - index.jsx - Expenses - index.jsx - Investments - index.jsx - index.js - App.jsx App.jsx function App() { return ( <Routes> {/* COMMON ROUTES */} <Route path="/todos" element={<Register />} /> <Route path="/activate/pending" element={<PendingActivation />} /> <Route path="/activate" element={<Activate />} /> <Route path="/login" element={<Login />} /> {/* APP ROUTES */} <Route path="/todos" element={<Todo />} /> <Route path="/expenses" element={<Expenses />} /> <Route path="/investments" element={<Investments />} /> </Routes> ); } function AppWrapper() { return ( <Provider store={store}> <BrowserRouter> <Alerts /> <App /> </BrowserRouter> </Provider> ); } ReactDOM.render(<AppWrapper />, document.getElementById('root')); Based on the endpoints, I will route the User to one of the sub-apps. Backend: And this is how I structured my backend (Django project): backend - app # project - settings.py - base # app 0 - has custom User model - todo # app 1 - to maintain todo list - expenses # app 2 - to maintain budget - Investments … -
Styling a checkbox in django template
I have a file (bs4_form.html) that handles my django form, that i just include in my html template (contest_form.html), but for some reason my checkbox isn’t displaying well… bs4__form.html {% load widget_tweaks %} {{ form.media }} {% for hidden_field in form.hidden_fields %} {{ hidden_field }} {% endfor %} {% if form.non_field_errors %} <div class="alert alert-danger" role="alert"> {% for error in form.non_field_errors %} {{ error }} {% endfor %} </div> {% endif %} {% for field in form.visible_fields %} <!----> <div class="row"> <div class="col-12"> <div class="mb-1"> <!----> <div class="form-group"> {% render_field field.label_tag %} {% if form.is_bound %} {% if field.errors %} {% render_field field class="form-control is-invalid" %} {% for error in field.errors %} <div class="invalid-feedback"> {{ error }} </div> {% endfor %} {% else %} <div> {% render_field field class="form-control" class="is-valid" %} </div> {% endif %} {% else %} <div> {% render_field field class="form-control" %} </div> {% endif %} {% if field.help_text %} <small class="form-text text-muted">{{ field.help_text }}</small> {% endif %} </div> <!----> </div> </div> </div> <!----> {% endfor %} contest_form.html {% extends 'contest/base.html' %} {% load static %} {% block content %} … <!----> <form method="post" enctype="multipart/form-data" novalidate> {% csrf_token %} {% include 'contest/bs4_form.html' with form=form %} <button type="submit" class="btn … -
Django - Accessing the same view with complex lengthy algorithm by several users in the same time
I am trying to implement an anonymous chat web application in Django. Right now I am on the stage where I need to connect users with each other based on their preferences, location etc. So I have a view find_room(request), where I am executing lengthy algorithm which runs for a few seconds, trying to find the closest user who is also searching for other users using the same view. So my problem is that when one user is calling the find_room view and then the other user calling the same view, then the second user should wait until first users's call is ended. So basically I need this view to be executed as a separate thread, so that several users can call this view and use this searching algorithm in the same time. Is there any functionality inside django that can help me? Or are there any other technologies I should use? (I heard about celery, but not sure if this is right thing for my purposes). Sorry if the question is confusing, and thanks for the answers! -
My registered accounts in herokuapp is not shown in django admin
I have created a django app and deployed it in Heroku. The web app works fine and the user registration and login works too. But when I open the django admin site it doesn't show the latest registered account. I have asked a few people to test my system so surely, there will be a few new accounts but the only accounts there were the ones I tested with a dummy account before deploying in heroku. This is my admin.py from django.contrib import admin # Register your models here. settings.py """ Django settings for sentiment_emotion_analysis project. Generated by 'django-admin startproject' using Django 2.1.7. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sentiment.settings") # import django # django.setup() # from django.core.management import call_command from django.contrib.messages import constants as messages MESSAGE_TAGS = { messages.DEBUG: 'alert-debug', messages.INFO: 'alert-info', messages.SUCCESS: 'success', messages.WARNING: 'alert-warning', messages.ERROR: 'danger', } # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'g&x!0fjh8c8)e_-z@gs1^lbngvqwk2(o3s(5zg!o&woxdsu_un' # SECURITY WARNING: don't … -
django and gurobi in docker have permission issues
I am trying to create a docker image for Django + Gurobi. Container runs as root by default. Gurobi does not want to run as root since license is issued to non-root user. If switching to non-root, Django's python complains "attempt to write a read-only database" using /db.sqlite3. chown+chmod just /apps, /db.sqlite3, and /usr/local/lib/python3.9/site-packages/django/db/backends/sqlite3 did not help. problem seems to go away if I chown and chmod 777 the entire container: bad idea What is the solution? Below is the Dockerfile FROM python:3.9 COPY . . ADD data . # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ENV APP_USER=user32 ENV APP_HOME=/home/$APP_USER # install python dependencies RUN pip install --trusted-host pypi.org --trusted-host pypi.python.org --trusted-host files.pythonhosted.org --upgrade pip RUN pip install --trusted-host pypi.org --trusted-host pypi.python.org --trusted-host files.pythonhosted.org --no-cache-dir -r requirements.txt RUN apt-get update && apt-get install -y inetutils-ping RUN tar xvzf gurobi9.5.0_linux64.tar.gz ENV GUROBI_HOME /gurobi950/linux64 RUN cd /gurobi950/linux64 && python setup.py install RUN rm gurobi9.5.0_linux64.tar.gz RUN groupadd -r $APP_USER && \ useradd -r -g $APP_USER -d $APP_HOME -s /sbin/nologin -c "Docker image user" $APP_USER ENV TZ 'America/Los_Angeles' RUN echo $TZ > /etc/timezone && apt-get update && \ apt-get install -y tzdata && \ rm /etc/localtime && \ ln -snf /usr/share/zoneinfo/$TZ … -
Features in django project
I have made a summary generation project using django. I need help with some of the feature such as adding bulk data in database using a form. and displaying multiple querysets in a single html table. Can anyone help me with this? -
django template not rendering folder images
here is my code bellow. views.py def galerry(request): result = request.GET.get('folder') print(result) imageList = [] directory = settings.MEDIA_ROOT for file in os.listdir(directory+"images/"): filename = os.fsdecode(file) if filename.endswith(".jpeg") or filename.endswith(".png"): src = os.path.join(directory, filename) imageList.append(src) print(filename) json_object1 = json.dumps(imageList) print(type(json_object1)) response = json.loads(json_object1) print(type(response)) print("json conversion", json_object1) return render(request, "galerry.html", context={'json_object1': response}) The loop worked fine i got all the files in the folder using print function but the image link seems not found in djando template. galerry.html file {% for item in json_object1 %} <img src="{{item}}" alt="test" height="200"> {% endfor %} settings STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_root") MEDIA_URL = '/images/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "gallery/static_cdn/") im getting Not Found: /Users/joejoe/Desktop/Gallery/gallery/static_cdn/05.jpeg [15/Jan/2022 04:57:05] "GET /Users/joejoe/Desktop/Gallery/gallery/static_cdn/01.jpeg HTTP/1.1" 404 1828 thanks will appreciate your help -
Add new update delete edit is not working
In this project, add new, edit, delete and update is not working. The code is correct but when I click submit, update It is not working. Please tell me Where I got wrong. Please tell me. urls.py: from django.contrib import admin from django.urls import path from master import views from django.conf.urls.static import static from mysite6 import settings urlpatterns = [ path('admin/', admin.site.urls), path('control/', views.controlindex), path('controladdnew',views.controladdnew), path('controledit/<int:id>', views.controledit), path('controlupdate/<int:id>', views.controlupdate), path('controldelete/<int:id>', views.controldestroy), ]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) views.py: from django.shortcuts import render,redirect from django.http import HttpResponseRedirect from master.forms import ControlmachineForm from master.models import Controlmachine # Create your views here. def control(request): if request.method == 'POST': form = ControlmachineForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['control_uploadfile']) model_instance = form.save() model_instance.save() else: form = ControlmachineForm() controlmachiness = Controlmachine.objects.all() return render(request,'master/control_uploadfile.html',{'form':form,'controlmachiness':controlmachiness}) def handle_uploaded_file(f): with open('master/static/upload/'+f.name, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) def controladdnew(request): if request.method == "POST": form = ControlmachineForm(request.POST) if form.is_valid(): try: form.save() return HttpResponseRedirect('/control/') except: pass else: form = ControlmachineForm() return render(request,'master/control_index.html',{'form':form}) def controlindex(request): controlmachines = Controlmachine.objects.all() return render(request,"master/control_show.html",{'controlmachines':controlmachines}) def controledit(request, id): controlmachine = Controlmachine.objects.get(id=id) return render(request,'master/control_edit.html', {'controlmachine':controlmachine}) def controlupdate(request, id): controlmachine = Controlmachine.objects.get(id=id) form = ControlmachineForm(request.POST, instance = controlmachine) if form.is_valid(): form.save() return HttpResponseRedirect('/control/') return render(request, 'master/control_edit.html', {'controlmachine': controlmachine}) def controldestroy(request, id): controlmachine = Controlmachine.objects.get(id=id) controlmachine.delete() … -
Url contains improper value
How would I pass the relative url from the page I came from. url.com/calendar -> click editprofile -> it does url.com/editprofile//calendar -> where I needed url.com/calendar urls.py path('editProfile/<str:page>/', editProfile, name='editProfile'), html: {% block content %} <form method = "POST" action='editProfile/{{request.get_full_path}}/' enctype="multipart/form-data"> {% csrf_token %} {{ editProfileForm.as_p }} <input type="submit" name="editProfileForm" value="Upload"> </form> {% endblock %} views.py @login_required @require_http_methods(["POST"]) def editProfile(request,page): context={} editProfileForm = UserProfileForm(request.POST or None, request.FILES or None,instance=request.user) # Rework this to get url and then set nmenu to that value print(page) if page =='': context['nmenu']='home' else: context['nmenu']=page if editProfileForm.is_valid(): editProfileForm.save() editProfileForm = UserProfileForm(instance=request.user) context['editProfileForm'] = editProfileForm context['is_post'] = False return render(request, "home.html", context) else: context['is_post'] = True context['editProfileForm'] = editProfileForm return render(request, "home.html", context) -
Is it possible to MOVE items in a database in django without deleting them?
I have a simple model in Django for a Library Manager. Inside there are 3 models. One to record all the books, another to issue the books and the last one to return the issued books. I already have the relationships done, but the problem arose when I wanted to issue a book. If a book is issued it should no longer be in the book records but rather be in the issued records. And when it is being returned it should go through the return class and get added to the book record. My question is "is it possible to move books in my case from on class to another?" -
Url and Path Issues in Django
from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('register`enter code here`, views.register, name='register'), path('login', views.login, name='login'), path('logout', views.logout, name='logout'), path('post', views.post, name='post'), path('postpage/<str:pk>', views.postpage, name='postpage'), ] -
HTML file in live mode in visual studio code?
My HTML file is in live mode. I cannot edit it and have to make modifications externally in notepad. Anyone can help me out? -
Not enough values to unpack error in production only
I recently launched my app on Heroku. When I run my app locally it works fine and I get no errors. For context, I recently switched my database from sqlite to PostgreSQL. When I run the app on Heroku I get the following ValueError. What could be causing this error to only occur in production and not locally? Traceback Environment: Request Method: POST Request URL: https://myurl.herokuapp.com/ Django Version: 3.2.10 Python Version: 3.9.9 Installed Applications: ['PRIIIME_Travel.apps.PriiimeTravelConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware') Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/PRIIIME_Travel/views.py", line 132, in get_ranking result1, result2, result3, result4, result5 = first_5_results_list Exception Type: ValueError at / Exception Value: not enough values to unpack (expected 5, got 0) views.py # list of each variable's broad category broad_variable_list = ["safety", "affordability", "transit", "language", "attractions", "climate"] # weighting of each variable ranking weight_variable1 = 0.33 weight_variable2 = 0.24 weight_variable3 = 0.17 weight_variable4 = 0.14 weight_variable5 = 0.12 def get_ranking(request): # if this is a POST request we need to process the form data if request.method … -
Django Forms: Default Value in get request
I am building a personal finance site that displays monthly transaction information on the homepage. I want the user to be able to switch months via a dropdown. Thankfully I already have the code built to filter on transaction date, what I am having trouble with is displaying a default value in the dropdown. The dropdown is populated by a dictionary (month_year_select) as you can see in forms.py below. I am not getting any error messages, the application just isn't performing the way I need. My question is how do I get the current month (Jan, 2022) to display by default in the dropdown when the user navigates to the homepage? The page already displays the current month's data, but the dropdown just lists the most recent month. I have looked through a ton of posts on this and the one that seems to have the closest explanation to what I need is here django forms: default values for bound forms I realize the views.py code is messy, I apologize in advance. I am new to python and would really appreciate any help you have to offer. Let me know if you need further explanation/other code examples. Thanks! python version … -
template not displaying info -django
I have no errors but my page wont show information from my template tagging. Please help! models.py class Department(models.Model): department_id = models.AutoField(primary_key=True) department_name = models.CharField(max_length=255,default = '') department_location = models.CharField(max_length=255,default = '') def __str__(self): return self.title urls.py urlpatterns = [ path('admin/', admin.site.urls), path('',views.home,name='home'), path('department',views.DepartmentClass.as_view(template_name='type/departmentdetails.html'),name='department'), ] views.py class DepartmentClass(TemplateView): def departments(request): departments = Department.objects.all() print(departments) return render(request,'type/departmentdetails.html', {'departments':departments}) departmentdetails.html {% for i in departments %} <tr> <td>{{i.department_name}}</td> <td>{{i.department_location}}</td> </tr> {% endfor %} the data i have saved on django/admin console wont show up on my webpage where is my code wrong please help!! -
I am trying to add a new field to the default Django Form and am getting an error when I'm trying to import a class from a forms.py file I made
The error is occurring in views.py file in which when I try to import the form class I made from my forms .py file I get an error of... Import ".forms" could not be resolved Here is what my views.py file looks like: from django.shortcuts import render, redirect from .forms import RegisterForm # Create your views here. def register(response): if response.method == "POST": form = RegisterForm(response.POST) if form.is_valid(): form.save() return redirect("/home") else: form = RegisterForm() return render(response,"register/register.html",{"form":form}) And here is my forms.py file from django import forms from django.contrib.auth import login, authenticate from django.contrib.auth import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class RegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ["username", "email", "password1", "password2"] Why am I getting that error/what am I missing? -
SQLite seems to ignore db_table parameter when running tests on MacOS but works fine on Ubuntu
So, the problem is when I'm running Django tests on MacOS I'm getting the following errors: Traceback (most recent call last): ... django.db.utils.OperationalError: no such table: main.estimates_estimate The above exception was the direct cause of the following exception: Traceback (most recent call last): ... raise CommandError( django.core.management.base.CommandError: Database file:memorydb_default?mode=memory&cache=shared couldn't be flushed. Possible reasons: * The database isn't running or isn't configured correctly. * At least one of the expected database tables doesn't exist. * The SQL was invalid. Hint: Look at the output of 'django-admin sqlflush'. That's the SQL this command wasn't able to run However, it passes if I change database to MySQL. Also, it passes on Ubuntu 20.04 with SQLite as DB backend. It just seems like db_table option of a model is ignored for some reason. class Estimate(models.Model): class Meta: db_table = "estimates" On Ubuntu db.sqlite3 has estimates table after the tests run is complete but on MacOS there is estimates_estimate. What I've tried I was looking for any possible difference of sqlite on Mac/Linux but couldn't find anything related. Also, I have tried to remove __pycache__ dirs and different Django versions (2.2 and 3.2). I've created a dummy app with the same file structure and … -
What is `*args` in a Django BaseCommand handle function for?
The signature of BaseCommand.handle is handle(*args, **kwargs). The documentation example only uses the kwargs argument. Are there cases/ways to define command arguments/options such that they will appear as positional arguments to the handle function? -
ERROR when i run pip install mssql-django or pip install pyodbc
Getting below error but got the solution also, you just do the following steps Go to https://www.lfd.uci.edu/~gohlke/pythonlibs/#pyodbc Sownload suitable '".whl"' file (Make sure you choose the correct whl file. For example: If you are using Python 2.7 on a 64-bit machine choose '''pyodbc-4.0.32-cp310-cp310-win_amd64.whl'''.) run '''pip install pyodbc-4.0.32-cp310-cp310-win_amd64.whl''' and try again This was the error Running setup.py install for pyodbc ... error ERROR: Command errored out with exit status 1: command: 'C:\x\x\x\x\Programs\Python\Python310\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\xxxx\x\x\Local\Temp\pip-install-8j3hztgx\pyodbc_b5b6921fa34f4725a66d9248ff07177c\setup.py'"'"'; file='"'"'C:\Users\x\AppData\Local\Temp\pip-install-8j3hztgx\pyodbc_b5b6921fa34f4725a66d9248ff07177c\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(file) if os.path.exists(file) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\x\AppData\Local\Temp\pip-record-e9qbaui4\install-record.txt' --single-version-externally-managed --compile --install-headers 'C:\Users\x\AppData\Local\Programs\Python\Python310\Include\pyodbc' cwd: C:\Users\x\AppData\Local\Temp\pip-install-8j3hztgx\pyodbc_b5b6921fa34f4725a66d9248ff07177c Complete output (12 lines): running install running build running build_ext building 'pyodbc' extension creating build creating build\temp.win-amd64-3.10 creating build\temp.win-amd64-3.10\Release creating build\temp.win-amd64-3.10\Release\src C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.30.30705\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -DPYODBC_VERSION=4.0.32 -IC:\Users\x\AppData\Local\Programs\Python\Python310\include -IC:\Users\x\AppData\Local\Programs\Python\Python310\Include -IC:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.30.30705\include -IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.8\include\um /EHsc /T C:\Users\x\AppData\Local\Temp\pip-install-8j3hztgx\pyodbc_b5b6921fa34f4725a66d9248ff07177c\src\pyodbc.h(19): fatal error C1083: Cannot open include file: 'windows.h': No such file or directory error: command 'C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.30.30705\bin\HostX86\x64\cl.exe' failed with exi ---------------------------------------- ERROR: Command errored out with exit status 1: 'C:\Users\x\AppData\Local\Programs\Python\Python310\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\x\AppData\Local\Temp\pip-install-8j3hztgx\pyodbc_b5b6921fa34f4725a66d9248ff07177c\setup.py'"'"'; __file_n'"'"', open)(file) … -
set custom permission to model in Django
I have to set some permission to a model in Django because I have some operations in DRF and I need to know whether the user has permission to do it or not. My models : class Device(models.Model): type = models.ForeignKey(Type, on_delete=models.CASCADE) name = models.fields.CharField(max_length=36) ip = models.CharField(max_length=64, blank=True) password = models.CharField(max_length=62, blank=True) mac = models.CharField(max_length=17, blank=True) description = models.fields.TextField(max_length=600, blank=True) users = models.ManyToManyField(User,'users_device',through="UserMeta") status = models.BooleanField(default=False) def __str__(self): return self.name class UsersMeta(models.Model): type_choices = [ ("owner",'owner'), ('user','user'), ('admin','admin') ] user = models.ForeignKey(User,on_delete=models.DO_NOTHING,related_name='UserMeta_devices') device = models.ForeignKey(Device,models.CASCADE,related_name='UserMeta_device') type = models.CharField(max_length=8,choices=type_choices) token = models.UUIDField(default=uuid4, editable=False, unique=True) join_time = models.DateTimeField(auto_now_add=True) last_activate = models.DateTimeField(null=True,blank=True) I need specific permission access to the Device model depending on the User model in the UserMeta model. in the UserMeta, I have some choices permissions like: owner,admin,user, so I need to say if this User has permission OWNER, or anything else can do it or not. I don't is correct or not, if do you know pls say to me -
React unable to read property of undefined
Can't figure out where my mistake is. Not able to map through to display the list of blog comments. I'm using django and react. From the code below, I tried to assess each blog post with comments. But I'm not able to get the comment property from the blog. If I do something like {blog.title} I get the title of the blog back on the browser. Since comments are associated with each post I try to get different properties of comment from the blog object (just as I specified in the code below) but the Value I'm getting is undefined. and have the following blog post and blog comment models. class BlogComment(models.Model): post = models.ForeignKey(BlogPost, on_delete=models.SET_NULL, related_name="post_comment", null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name="user_comment", null=True) name = models.CharField(max_length=200, null=True, blank=True) comment = models.TextField(null=True, blank=True) dateCreated = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.user.username) class BlogPost(models.Model): ... author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) body = models.TextField() dateCreated = models.DateTimeField(auto_now_add=True) And the serializers for both models are: class CommentSerializer(serializers.ModelSerializer): class Meta: model = BlogComment fields = '__all__' class BlogPostSerializer(serializers.ModelSerializer): comments = serializers.SerializerMethodField(read_only=True) class Meta: model = BlogPost fields = "__all__" def get_comments(self, obj): comments = obj.comment_set.all() serializer = CommentSerializer(comments, many=True) return serializer.data <h2>{blog.title}</h2> <img src={blog.image} /> … -
Problem recovering django with pipenv after crash
I recently had a catastrophic hard drive failure and I had not pushed all of my recent commits to a remote repository (I have learned my lesson). Fortunately I did have a copy of most of my latest work. I recreated my local environment (I thought correctly but maybe not) and attempted to start the project with the files. When I run "pipenv shell" the env appears to activate and running "git branch" does show the two branches. However when I ran "python manage.py migrate" I received the following error: (sitefolder) user@users-MBP ohive % python manage.py migrate File "manage.py", line 17 ) from exc ^ SyntaxError: invalid syntax When I run "python -V" it returns 2.7.18. The python version should be 3.9.6. When I do start pipenv shell in a folder without the old files, the correct version is returned. Any ideas about how I can get the pipenv to use the correct version of python? -
Django ninja token authentication with djoser
I have implemented CRUD with Django Ninja framework, but now I want auth in my app, I had installed and config Djoser, so now I can generate tokens, but I don't know how to verify in my CRUD's class AuthBearer(HttpBearer): def authenticate(self, request, token): if token == "supersecret": return token @api.get("/bearer", auth=AuthBearer()) def bearer(request): return {"token": request.auth} I shoud able to check token inside "AuthBearer" function, but I don't know how my repo (link) -
Django custom login not authenticating
I am creating a custom user creation. the register user is working but not managing to login, works fine in admin but not through my form. My loginclass in forms.py class LoginForm(forms.Form): email = forms.EmailField(label='Email') password = forms.CharField(widget=forms.PasswordInput) def __init__(self, request, *args, **kwargs): self.request = request super(LoginForm, self).__init__(*args, **kwargs) def clean(self): request = self.request data = self.cleaned_data email = data.get("email") password = data.get("password") qs = User.objects.filter(email=email) if qs.exists(): # user email is registered, check active/ not_active = qs.filter(is_active=False) if not_active.exists(): raise forms.ValidationError("This user is inactive.") user = authenticate(request, email=email, password=password) if user is None: raise forms.ValidationError("Invalid credentials") login(request, user) self.user = user return data This is from my views.py User = get_user_model() def login_page(request): form = LoginForm(request.POST or None) context = { "form": form } if form.is_valid(): email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") user = authenticate(request, email=email, password=password) if user is not None: login(request, user) else: # Return an 'invalid login' error message. print("Error") return render(request, "accounts/login.html", context) In my settings.py i have set LOGIN_REDIRECT_URL = '/' My html is here <form method="post"> {% csrf_token %} {{ form.non_field_errors }} {{ form.source.errors }} {{ form.source }} <div class="form-group"> <input class="form-control" type="email" name="{{ form.email.name }}" id="{{ form.email.id_for_label }}" {% if form.email.value != …