Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
djangoPDF: FileNotFoundError: [WinError 2] The system cannot find the file specified
File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python38\lib\subprocess.py", line 1307, in _execute_child hp, ht, pid, tid = _winapi.CreateProcess(executable, args, FileNotFoundError: [WinError 2] Le fichier spécifié est introuvable hi; I want to display a PDF file in the navigator; knowing that I installed wkhtmltox-0.12.6-1.msvc2015-win64; but it gives me the following error message in browser: DoesNotExist at /scolar/Prise_en_chargeS2_PDFView/1/ Engagement matching query does not exist. Request Method: GET Request URL: http://127.0.0.1:8000/scolar/Prise_en_chargeS2_PDFView/1/ Django Version: 2.2.10 Exception Type: DoesNotExist Exception Value: Engagement matching query does not exist. Exception Location: C:\Users\LENOVO\workspace\budgetenv\lib\site-packages\django\db\models\query.py in get, line 406 Python Executable: C:\Users\LENOVO\workspace\budgetenv\Scripts\python.exe Python Version: 3.8.0 Python Path: ['C:\Users\LENOVO\workspace\Project_GFC_Remote', 'C:\Users\LENOVO\AppData\Local\Programs\Python\Python38\DLLs', 'C:\Users\LENOVO\AppData\Local\Programs\Python\Python38\lib', 'C:\Users\LENOVO\AppData\Local\Programs\Python\Python38', 'C:\Users\LENOVO\workspace\budgetenv', in eclipse: File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python38\lib\subprocess.py", line 1307, in _execute_child hp, ht, pid, tid = _winapi.CreateProcess(executable, args, FileNotFoundError: [WinError 2] Le fichier spécifié est introuvable File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python38\lib\subprocess.py", line 1307, in _execute_child hp, ht, pid, tid = _winapi.CreateProcess(executable, args, FileNotFoundError: [WinError 2] Le fichier spécifié est introuvable need help emergency -
How to use different Pydantic Model in a view to create and respond
Im currently trying to understand the Pydantic FastAPI setup within my Django app and have the following issue: When I create a new Order object, I want to return the newly created object using a different Pydantic model as I use for the creation (as after the creation I now have the ID of the order that I can also return). # routes # Create a new Order @router.post("/create/", response_model=schemas.OrderResponse) def create_orders(order: schemas.OrderResponse): return views.create_order(order=order) # views.py from uuid import UUID from . import models, schemas # Create a new order def create_order(order: schemas.OrderResponse): new_order = models.Order.objects.get_or_create(order) return new_order # schemas.py # pydantic models from uuid import UUID from pydantic import BaseModel # Base Class for Model "Order" class OrderBase(BaseModel): product: str period: str power: int side: str class Config: orm_mode = True class OrderResponse(OrderBase): id: UUID When I now send an API request with this body: { "product": "Base", "period": "Hour", "power": 10, "side": "Buy" } I get this error -- how to set it up such that when creating the instance it doesnt validate for the UUID and after creation and when returning the instance it includes the UUID in the response? { "detail": [ { "loc": [ … -
Docker Image works with docker-compose up but not on Amazon ECS or Heroku
I am trying to host a Django project with a Postgres database in a Docker container. The project is a practice e-commerce site with a database for product info. I was able to get it working with docker-compose up and accessed the site running in the container at localhost:8000 but when I tried hosting it on AWS it didn't work. I uploaded the image to ECR and started a cluster. When I tried running a task with the image, it showed PENDING but as soon as I tried to refresh, the task was gone. I tried setting up cloudwatch logs but they were empty since the task was stopping immediately after starting. After that I tried hosting on Heroku. I was able to deploy the image but when I tried to open the app it showed an error (shown below). It feels like the image is just failing immediately whenever I try hosting it anywhere, but it works fine when I use docker-compose up. I think I'm making a very basic mistake (I'm a total beginner at all this) but not sure what it is. Thanks for taking the time to help. I'll also add my Dockerfile and docker-compose.yml Error … -
Cannot edit user profile and change password of the custom user in django
I have a custom user model in my django project. I can create users using the form based on this model but I'm unable to edit and change the passwords. How can I make this possible? Created the custom user models as shown below. from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): class Role(models.TextChoices): ADMIN = 'ADMIN', 'Admin' DEVELOPER = 'DEVELOPER', 'Developer' TESTER = 'TESTER', 'Tester' base_role = Role.ADMIN role = models.CharField(max_length=20, choices= Role.choices) def save(self, *args,**kwargs): if not self.pk: self.role = self.base_role return super().save(*args, **kwargs) I tried to edit the user the profile and change password using this form. from django.contrib.auth.forms import UserCreationForm from .models import User from django import forms class RegisterUserForm(UserCreationForm): email = forms.EmailField() first_name = forms.CharField(max_length=50) last_name = forms.CharField(max_length=50) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email','role', 'password1', 'password2') class EditUserForm(forms.ModelForm): email = forms.EmailField() first_name = forms.CharField(max_length=50) last_name = forms.CharField(max_length=50) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email') corresponding views.py file from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout from django.contrib import messages from django.views.decorators.cache import never_cache from .forms import RegisterUserForm, EditUserForm from django.views import generic from django.urls import reverse_lazy from django.contrib.auth.views import PasswordChangeView from … -
Sent an extra field to serializers -DRF
I have a ModelSerializer with fields from the table SubscriptionsPlans. serializer.py class SubscriptionSerializer(serializers.ModelSerializer): class Meta: model = SubscriptionsPlans fields = { 'id', 'name', 'plan_type', 'plan_details', 'price' } I want to sent an extra field name sub_id into this serializer from views. This sub_id will be True or False depending on a table SubscriptionsOrder. If SubscriptionsOrder has rows then the sub_id will be a True else False. SubscriptionsOrder for a specific user is looked here. views.py class SubscriptionView(APIView): def get(self, request): get_sub_id = SubscriptionsOrder.objects.filter(id=request.user).first() sub_id = get_sub_id.plan_selected subscription_details = SubscriptionsPlans.objects.filter(is_deleted=False) user_serializer = SubscriptionSerializer(subscription_details) return Response(user_serializer.data) I want to sent sub_id along with the user_serializer. models.py class SubscriptionsPlans(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=255) plan_type = models.CharField(max_length=255) plan_details = models.TextField(max_length=1000) request_per_month = models.IntegerField() price = models.FloatField() is_deleted = models.BooleanField(default=False) created_at = models.DateTimeField() updated_at = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = 'Subscription Plans' verbose_name_plural = 'Subscription Plans' class SubscriptionsOrder(models.Model): id = models.IntegerField(primary_key=True) user_id = models.ForeignKey( AppUser, null=True, on_delete=models.SET_NULL ) plan_selected = models.ForeignKey(SubscriptionsPlans, null=True,on_delete=models.SET_NULL) billing_info = models.IntegerField() payment_info = models.IntegerField() class Meta: verbose_name = 'Subscription Order' verbose_name_plural = 'Subscription Order' before sending sub_id the output looks like this { "id": 1, "name": "Professional", "plan_type": "MONTHLY", "plan_details": "{'Details'}", "price": 50.0 }, { "id": 2, "name": "Business", … -
Getting product items from Products table with id's saved in CartItems table (django, sqlite)
I'm new to django and in backend development in general, as well as databases. I have a CartItems and Products models in django. In the CartItems there's only id and product_id columns. How can I get all the products saved in CartItems using the product_id? What I did so far was to use a for loop in CartItems and used the product_id as a parameter to do Products.objects.get(id=id) and append() it to an empty list. And It works. cart_details = [] for item in cart_items: cart_details.append(Products.objects.get(id=item.product_id)) Is this the way to do it? If there's a better way please let me know. Thank you! -
How to get the table details based on post request django
**views.py** from django.shortcuts import render import pymysql from django.http import HttpResponseRedirect from facligoapp.models import Scrapper from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger def index(request): user_list = Scrapper.objects.all() page = request.GET.get('page', 1) paginator = Paginator(user_list, 5) try: users = paginator.page(page) except PageNotAnInteger: users = paginator.page(1) except EmptyPage: users = paginator.page(paginator.num_pages) return render(request, "home.html", { 'users': users }) if request.method == "POST": from_date = request.POST.get("from_date") print(from_date) to_date = request.POST.get("to_date") print(to_date) **home.html** <!DOCTYPE html> <html> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script> <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> <body> <style> h2 {text-align: center;} </style> <h1>Facilgo Completed Jobs</h1> <form action="" method="post"> {% csrf_token %} <label for="from_date">From Date:</label> <input type="date" id="from_date" name="from_date"> <label for="to_date">To Date:</label> <input type="date" id="to_date" name="to_date"> <input type="submit"><br> </form> <div class="container"> <div class="row"> <div class="col-md-12"> <h2>Summary Details</h2> <table id="bootstrapdatatable" class="table table-striped table-bordered" width="100%"> <thead> <tr> <th>user_registration_source_id</th> <th>user_type</th> <th>user_id</th> <th>source</th> <th>source_url</th> <th>created at</th> <th>updated at</th> </tr> </thead> <tbody> {% for stud in users %} {% csrf_token %} <tr> <td>{{stud.user_registration_source_id}}</td> <td>{{stud.user_type}}</td> <td>{{stud.user_id}}</td> <td>{{stud.source}}</td> <td>{{stud.source_url}}</td> <td>{{stud.created_at}}</td> <td>{{stud.updated_at}}</td> </tr> {% endfor %} </tbody> </table> {% if users.has_other_pages %} <ul class="pagination"> {% if users.has_previous %} <li><a href="?page={{ users.previous_page_number }}">«</a></li> {% else %} <li class="disabled"><span>«</span></li> {% endif %} {% if user.number|add:'-4' > 1 %} <li><a href="?page={{ page_obj.number|add:'-5' }}">&hellip;</a></li> … -
Django throttling problem when use ManualAPIKey
I am using Django rest API, in one of the views I use manual key authentication when I activate throttling for that view, the request from a same IP address with different API_key count as from same user and reject after several times. For example: I set the rate 12/minute. user1 from a IP 20.40.5.6 send 10 request in a minute, and user2 from a IP 20.40.5.6 send 10 request in a minute. They both get 429 error until next minute. If these user send request from different IPs, there are no problems. class HasManualAPIKey(BasePermission): def has_permission(self, request, view): key = request.META["HTTP_AUTHORIZATION"].split()[1] keys = MyUser.objects.values_list('key', flat=True) if key in keys: return True else: return False class MyUserRateThrottle(UserRateThrottle): rate= '12/minute' class MyUserView(APIView): permission_classes = [HasManualAPIKey] throttle_classes = [DeviceRateThrottle] -
Django Rest Framework : how to specify a serializer to use different fields to create, update and get
I have a doubt with the serializers and so far I have not been able to solve it. I explain the doubt with the following example: I have a User model and this model has the following attributes: username, password, first_name, last_name, age, gender. I also have a serializer, which is called UserSerializer. The UserSerializer should do the following: When inserting information into the database, UserSerializer should only take into account the fields: username, password, first_name, last_name. When retrieving information from the database, UserSerializer should only take into account the fields: age, gender. When updating the database information, UserSerializer should only take into account the fields: password. My solution: class UserSerializer: class UserCreateSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'password', 'first_name', 'last_name'] class UserGetSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['age', 'gender'] class UserUpdateSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['password'] Question: The question: is there any way to synthesize the three serializers into one, or what is the best solution for this problem? Thank you very much. -
CORS error appears when I Upload multiple files at once to S3 Bucket with boto3
I have a question about S3 upload, I use boto3 library in python to connect to S3. def get_client(): return boto3.client('s3', aws_access_key_id = 'AWS_ACCESS_KEY', aws_secret_access_key = 'AWS_SECRET_KEY') My Multiple upload file in below for item in img_files: file_type = '' uuid_key = uuid.uuid4() fs = FileSystemStorage() filename = fs.save(f'{S3_TEMP_FOLDER}{uuid_key}-{item.name}', item) file_o_name, file_o_ext = os.path.splitext(filename) if file_o_ext.lower() in ['.jpg', '.png', '.jpeg']: file_type = 'image' else: file_type = 'video' uploaded_file_path = fs.path(filename) try: s3_client.upload_file(uploaded_file_path, bucket_name, f'{folder_key}/{uuid_key}-{item.name}', ExtraArgs={'ACL': 'public-read'}) uploaded_data = { "file_name": item.name, "file_key": f'{folder_key}/{uuid_key}-{item.name}', "bucket_name": bucket_name, "folder_id": get_folder_id.id, "created_by": request.user.username, "updated_by": request.user.username, "bucket_id": bucket.id, "file_type": file_type } S3FileManagement.objects.create(**uploaded_data) except Exception as e: logger.error({'message': str(e)}) logger.error({'message': S3_FOLDER_MESSAGE['S3_FILE_UPLOAD_FAILED']}) return Response({'message': S3_FOLDER_MESSAGE['S3_FILE_UPLOAD_FAILED']}, status=status.HTTP_400_BAD_REQUEST) When I upload about 5-10 files at a time, the upload process is no problem, but when I upload > 30 files, there will be some files with 502 - CORS errors. In settings python, I was allows CORS CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOWED_ORIGINS = [ '..{url}..vercel.app', ] CSRF_TRUSTED_ORIGINS = [ '..{url}..vercel.app', ] Additionaly, the python backend I'm using aapanel. Any more additional settings needed? Thanks. -
Django FormView and ListView multiple inheritance error
Problem I have a AccesCheck Mixin, and view named ListFormView that inherits AccessCheck, FormView and ListView to show list and create/update Worker objects. But when I try to add new data by POST method, django keeps returning Attribute Error : Worker object has no attribute 'object_list' error. What is more confusing to me is that whole ListFormView is duplication of another class based view that is used in another app, and the original one is running without any problems. I've doublechecked all my codes and still have no clue to fix this problem. [AccessCheck] class AccessCheck(LoginRequiredMixin, UserPassesTestMixin, View): def test_func(self, *args, **kwargs): access = [x.id for x in Auth.objects.filter(auth_id = self.kwargs['target'])] return self.request.user.is_superuser or selr.request.user.id in access def handle_no_permission(self): return redirect('index') get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['shop'] = Shop.objects.get(shop_id = self.kwars['shop_id']) return context [ListFormView] class Worker(AccessCheck, FormView, ListView): template_name = 'my_template_name.html' context_object_name = 'workers' form_class = WorkerForm success_url = './my_url' def form_valid(self, form): data = form.save() return super().form_valid(form) def get_queryset(self, *args, **kwargs): return Worker.objects.filter(shop_id = self.kwargs['shop_id']) -
django migration error on changing FK field to regular field
Part of my model looked like this, initially. class RealTimeLocation(models.Model): name = models.CharField(max_length=80) latlng = models.PointField(default=None) class CabLog(models.Model): location = models.ForeignKey(RealTimeLocation, on_delete=models.CASCADE, related_name='cablog_locations') Then i thought, no need for an FK field, so i changed the fk field to a Point field. class RealTimeLocation(models.Model): name = models.CharField(max_length=80) latlng = models.PointField(default=None) class CabLog(models.Model): location = models.PointField()// 'python manage.py makemigrations ' no issues, but on migrate i'm getting error. .django.db.utils.ProgrammingError: column "location_id" of relation "myapp_cablog" does not exist. I tried adding a null=True option to pointfield, deleting the migrate-scripts and redo it many times, no avail. SO before i completely fake-migrate the entire project and startover, do anybody have any solutions for this. I already got some data in DB, so i really don't want to do that. Thanks. -
Is it possible to create an empty csv file in Django database?
I am wondering if it is possible to create an empty csv file in Django database. Basically what I am trying to do is to allow the user to upload a text file as TextUpload model object, then run the code in the backend to process the text file and to save it as ProcessedTextToCsv model object. My views.py code looks something like this: def upload_view(request): form = TextUploadsModelform(request.POST or None, request.FILES or None) if form.is_valid(): form.save() form = TextUploadsModelform() ProcessedTextToCsv().save() I am wondering if here I can create an empty csv so I can use file_name.path as argument in the function below processTextToCsv(TextUploads.objects.latest('uploaded').file_name.path,ProcessedTextToCsv.objects.latest('uploaded').file_name.path) return render(request, 'main_app/example.html',{'form': form}) -
Dockerized Django app not running in Azure
I'm trying to deploy a Django app dockerized to Azure App Service, the app seems to run well on my local environment http://localhost:8000/, for this I use docker run -p 8000:8000 myapp.azurecr.io/myapp:latest. But when I try deploying the app to Azure it doesn't work. This is my dockerfile: FROM python:3.8.3-slim ENV PYTHONUNBUFFERED=1 WORKDIR /app RUN apk update \&& apk add --no-cache gcc musl-dev postgresql-dev python3-dev libffi-dev freetype-dev libxml2-dev libxslt-dev build-base \&& pip install --upgrade pip psycopg2-binary COPY ./requirements.txt ./ RUN pip install -r requirements.txt COPY ./ ./ EXPOSE 3000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] And these are the logs I receive from Azure 2022-11-25T00:33:44.857803391Z Performing system checks... 2022-11-25T00:33:44.857871092Z 2022-11-25T00:33:48.431821909Z System check identified no issues (0 silenced). 2022-11-25T00:33:48.890144064Z November 25, 2022 - 00:33:48 2022-11-25T00:33:48.896514773Z Django version 4.0.3, using settings 'certificados.settings' 2022-11-25T00:33:48.896531175Z Starting development server at http://0.0.0.0:8000/ 2022-11-25T00:33:48.896535775Z Quit the server with CONTROL-C. ... Container myapp_0_aaaaa didn't respond to HTTP pings on port: 3000, failing site start. I'm new to Docker so I don't know if I'm missing something important here. -
How to solve CORS error caused from API Calls made by Chrome extension DOM element inserted to a webpage
Im trying to make an API request to my backend server (Django) from the chrome extension. The API request goes through from the Popup.html and Popup.js but I'm facing the CORS issue when I am trying to make the request via a custom DOM element which I had inserted into Webpage. For example: I want to fetch the list of users. The Api request works fine when I open the chrome extension and make the API request. When I make the same API request after insert a new DOM element from chrome extension into any Webpage. The API is throwing CORS error. As the origin inside request headers get set to the current webpage which is not inside my allowed origin. Is there any way in which we can resolve the CORS issue without adding the LinkedIn website Url to allowed origins. I have tried multiple implementations all of which failed miserably. -
How to filter foreign key choices in admin form based on another field while changing (before saving)
I have a model with two foreign key fields class LabTesting(models.Model): fk_farm = models.ForeignKey("Farm", verbose_name=_("Farm"), on_delete=models.SET_NULL, null=True, blank=True) fk_house = models.ForeignKey("House", verbose_name=_("House"), on_delete=models.SET_NULL, null=True, blank=True) fk_house has a fk_farm foreign key field I want to limit the fk_house choices in admin page to the selected farm but while changing before clicking save I tried to edit the form but I couldn't get it to work dynamically in the change list page without saving the object -
How to render sphinx static files in django view
I have a sphinx documentation and django projet in two separate folder. When I try to render the sphinx template in my django projet, I loose all the css style and js link. Is there a way load all dependencies? -
Django - How to track user progress across multiple days?
I have a django model that updates with the user's current time spent on the website: totallearningtime = models.DecimalField(default = 0, decimal_places=2, max_digits=100) # total time user spent on website And I have the following chart.js that I want to populate with the totallearningtime through the week, and reset at the begining of the next week: (right now it has placeholder values) Here is the code for the chart: <script> const ctx = document.getElementById("myChart"); // <block:setup:1> const DATA_COUNT = 12; const labels = [ "Mon", "Tue", "Wen", "Thur", "Fri", "Sat", "Sun", ]; const datapoints = [ 0, 20, 20, 60, 60, 120, 140, 180, 120, 125, 105, 110, 170, ]; const data = { labels: labels, datasets: [ { label: "Learning Time", data: datapoints, // borderColor: red, fill: false, cubicInterpolationMode: "monotone", tension: 0.4, }, ], }; new Chart(ctx, { type: "line", data: data, options: { responsive: true, maintainAspectRatio: true, plugins: { title: { display: false, text: "Total Time: 5h 45m", }, }, interaction: { intersect: false, }, scales: { x: { display: true, title: { display: true, }, }, y: { display: true, title: { display: true, text: "Hours", }, suggestedMin: 0, suggestedMax: 200, }, }, }, }); </script> However, … -
How to add field to every historical model in django simple history
Tracking which change to a model has been made is easy. But tracking which changes have been conducted together during a single "operation" or "action" is more difficult. I would like to add an additional field to all historical models that stores a key referencing the action during which an object has been changed. In order to add a field to a historical model that is generated by the django-simple-history package one has to add an abstract class for each model and install a model specific signal handler in the apps' config. When working with 50+ models this is quiet a lot of unDRY code. How would I add a field to all historical models? -
Pydantic raises ValidationError not allowing "None" using FastAPI and Django ORM
So I have the following model in my database (Django ORM): # Database Models handled by Django ORM import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "superpower.settings") import django django.setup() from django.db import models class Order(models.Model): """Test Table""" text = models.CharField(max_length=50) amount = models.IntegerField() the following Pydantic schema: from pydantic import BaseModel # Base Class for Model "Order" class OrderBase(BaseModel): text: str amount: int class Config: orm_mode = True this view: from . import models, schemas def create_order(order: schemas.OrderBase): models.Order.objects.get_or_create(text=order.text, amount=order.amount) and finally the following routes: from fastapi import APIRouter, Depends, HTTPException from .. import models, schemas, views router = APIRouter( prefix="/orders", tags=["orders"], responses={404: {"description": "Not found"}}, ) @router.post("/create/", response_model=schemas.OrderBase) def create_orders(order: schemas.OrderBase): return views.create_order(order=order) When I now call http://127.0.0.1:8000/api/orders/create with the body { "text": "test1", "amount": 40 } I get this error: File "/Users/jonas/Desktop/superpower/venv/lib/python3.10/site-packages/uvicorn/protocols/http/h11_impl.py", line 407, in run_asgi result = await app( # type: ignore[func-returns-value] File "/Users/jonas/Desktop/superpower/venv/lib/python3.10/site-packages/uvicorn/middleware/proxy_headers.py", line 78, in __call__ return await self.app(scope, receive, send) File "/Users/jonas/Desktop/superpower/venv/lib/python3.10/site-packages/fastapi/applications.py", line 270, in __call__ await super().__call__(scope, receive, send) File "/Users/jonas/Desktop/superpower/venv/lib/python3.10/site-packages/starlette/applications.py", line 124, in __call__ await self.middleware_stack(scope, receive, send) File "/Users/jonas/Desktop/superpower/venv/lib/python3.10/site-packages/starlette/middleware/errors.py", line 184, in __call__ raise exc File "/Users/jonas/Desktop/superpower/venv/lib/python3.10/site-packages/starlette/middleware/errors.py", line 162, in __call__ await self.app(scope, receive, _send) File "/Users/jonas/Desktop/superpower/venv/lib/python3.10/site-packages/starlette/middleware/exceptions.py", line 79, in __call__ raise exc File "/Users/jonas/Desktop/superpower/venv/lib/python3.10/site-packages/starlette/middleware/exceptions.py", … -
Django Can't See Where I Typed in User ID
So I'm creating a web app in Django, and I encountered this error: my urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('<int:user_id>/', views.profile, name="profile"), #path('signup/', views.signup, name="signup"), path("signup/", views.signup, name="signup") ] my views.py: from django.shortcuts import render, get_object_or_404 from django.contrib.auth import forms from django.urls import reverse_lazy from django.http import HttpResponse, Http404 from django.template import loader from .models import User from .forms import SignUpForm from datetime import datetime def index(request): cool_people_list = User.objects.order_by("-username")[:5] _template = loader.get_template("front_page.html") context = { "cool_people_list" : cool_people_list, } return HttpResponse(_template.render(context, request)) def profile(request, user_id): try: user = get_object_or_404(User, pk=user_id) _template = loader.get_template("profile.html") context = { "user" : user } return HttpResponse(_template.render(context, request)) except: raise Http404("The user you are looking for doesn't exist.") def signup(request): if request.method == "POST": form = SignUpForm(request.POST) if form.is_valid(): rn = str(datetime.today().strftime("%Y-%m-%D")) rn2 = str(datetime.today) """usr_list = User.objects.order_by('-join_date') latest_usr = usr_list.first()""" new_user = User(3, str(form.cleaned_data.get("username")), str(form.cleaned_data.get("password")), rn, rn2) new_user.save() return render(request, "signup.html") my models.py: from django.db import models from django.core.validators import MinLengthValidator import datetime class User(models.Model): user_id = models.IntegerField(unique=True) username = models.CharField(max_length=25, validators=[MinLengthValidator(3)]) password = models.CharField(max_length=25, validators=[MinLengthValidator(7)]) join_date = models.DateField() last_online = models.DateTimeField() def __str__(self): return self.username I kept trying different methods, like manually … -
Django how to register model users to admin panel
I am making a site, the idea is that users can post and comment, but i messed up the models(i think) and now i have 2 seperate groups of users. My goal is to combine these 2 groups that they would be able to post and comment. When i login with an admin user and try to post something i can only use the users that i have created from the model(i have a dropdown menu that assigns and existing user to a post) I have: Admin panel users that can't post or comment, but can register, login and log out And: Model created users that can create posts and comment, but i assign them manually to posts/comments Here is my models User code: class User(models.Model): username = models.CharField('Username', max_length=100) description = HTMLField() interests = models.ManyToManyField(Interest, related_name='user_interest') Here is my models Post code: class Post(models.Model): **post_name = models.CharField('Post name', max_length=100)** description = HTMLField() updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) interest_tag = models.ManyToManyField(Interest, related_name='interest_tag') post_host = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) Here is my models Comment code: class Comment(models.Model): **user = models.ForeignKey(User, on_delete=models.CASCADE)** post = models.ForeignKey(Post, on_delete=models.CASCADE) body = models.TextField() updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) I'm pretty green so not sure how … -
how to extract value from FK
I have this org object (org1) which is showing in my page. This is reference to a foreign key in the model. When I do just {{ orgid }} I get the above, I can't figure out how to actually get the value - that Foreign Key = 'org1' Can anyone help please? -
How to fix a bug in Django
When I was working on a Django project (blog), I had an error(s) while working on the site. Here are the errors I have appeared: 1: When I entered the python command manage.py makemigrations blog(via the console) in the directory C:\mysite\site\miniproject , then there is this: Traceback (most recent call last): File "manage.py", line 23, in <module> main() File "manage.py", line 19, in main execute_from_command_line(sys.argv) File "C:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 395, in execute django.setup() File "C:\Program Files\Python36\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Program Files\Python36\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Program Files\Python36\lib\site-packages\django\apps\config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "C:\Program Files\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "C:\mysite\site\miniproject\blog\models.py", line 5, in <module> class Post(models.Model): File "C:\mysite\site\miniproject\blog\models.py", line 12, in Post author = models.ForeignKey(User, related_name='blog_posts') TypeError: __init__() missing 1 required positional argument: 'on_delete' Although I did everything according to the instructions on the website https://pocoz .gitbooks.io/django-v-primerah/content/sozdanie-i-primenenie-migracij.html. I … -
Django: Heroku Postgres resets uploaded data every idle
My problem seems to be the same as addressed in this page. However, I believe I am using an add-on for my case, specifically the Heroku Postgres. In case it is needed, here is a part of my settings.py: BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = env.str("SECRET_KEY") DEBUG = env.bool("DEBUG", default=False) ALLOWED_HOSTS = \[".herokuapp.com", "localhost", "127.0.0.1"\] CSRF_TRUSTED_ORIGINS = \['https://8000-abcdarl-hivforecastingd-4p274ahpjtp.ws-us67.gitpod.io'\] # Database DATABASES = { 'default': env.dj_db_url("DATABASE_URL") } # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.1/howto/static-files/ STATIC_URL = 'static/' STATICFILES_DIRS = \[BASE_DIR / 'static'\] STATIC_ROOT = BASE_DIR / 'staticfiles' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' # Default primary key field type # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' Here is a screenshot of my config variables: Screenshot of my config variables In my Django admin, I could still see all my uploaded files, but I could only download the recent ones and it would say not found in the previous ones. This is my first time deploying an application and using Heroku, so I am still new with every process involved. Thank you in advance. I don't know what to try as I am still new with everything, but I kept on researching how to handle it and I couldn't find …