Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Website that generates quotes from my db depens on 365 days
I like to create website that show quotes depends on days(365) for this how can create js function . Example: day 1 : hello day 2 : hi For today 1 : web sites print hello How can I create this for 365 days -
How can I join multiple models in Django into a virtual table?
If I have 3 models, like: class Cow(models.Model): name = number_of_eyes = number_of_feet = color = class Pig(models.Model): name = number_of_eyes = number_of_feet = intelligence = class Horse(models.Model): name = number_of_eyes = number_of_hooves = weight_capacity = speed = And I'm interested in making a single Livestock table in my template that has instances of all 3, but I'm only interested in these columns that all 3 models have: name number_of_eyes number_of_feet (number_of_hooves if Horse) And we can ignore all other columns. How can I join them into a single queryset? The end goal is to get a single virtual table (queryset) that I can do a few other operations on (order_by, slice), and then return the data in just those columns. Is this possible in the Django ORM? -
Django, successful login, but still anonymous user
Being anonymous user even after successful login, here is views.py: class LoginView(views.APIView): def post(self, request): data = serializers.LoginSerializer(data=request.data) print(data.is_valid()) print(data.errors) print(f" HEEERE::: {data}") if self.request.method == 'POST': if data.is_valid(): auth = authenticate( username=data.validated_data['email'], password=data.validated_data['password']) print(f" email check : {data.validated_data['email']}") print(f"auth:: {auth}") if auth is not None: login(request, auth) print("Hello World") return redirect("/somelink") else: return HttpResponse("Invalid Credentials") else: return HttpResponse("Data not being validated :O") class LogoutView(views.APIView): def post(self, request): logout(request) serializers.py class LoginSerializer(serializers.Serializer): email = serializers.EmailField() password = serializers.CharField(write_only=True) def validate(self, data): email = data.get("email") print(f" email here : {email}") password = data.get("password") user = authenticate(username=email, password=password) print(f"{user} username serializer ") print(f"this is data : {data}") if user is not None: return data raise serializers.ValidationError("Incorrect Credentials") in frontend side (React): login component: import React, { useState } from 'react'; import { Link , Redirect} from 'react-router-dom'; import { connect } from 'react-redux'; import { login } from '../actions/auth'; import axios from 'axios'; import Cookies from 'js-cookie'; function Login(){ let [login,setLogin,isLoggedin] = useState({ email: '', password:'' }); let cookie = Cookies.get('csrftoken'); const { email, password } = login; function handleChange(e){ console.log(e.target.value); setLogin({ ...login, [e.target.name]: e.target.value }); } function handleSubmit(e){ e.preventDefault(); axios.post(' http://127.0.0.1:8000/login/',login,{withCredentials:true},{headers: {'Content-Type': 'application/json', 'X-CSRFToken': cookie,'Access-Control-Allow-Origin':'*'}}) .then(res => { console.log(res.data); setLogin({ ...login, … -
Django Rest Framework: saving data into database from a particular input structure
This is my first time with Django Rest Framework. I have two particular models for storing data into the database whose are: class RuleTree(models.Model): ruleId = models.IntegerField(primary_key=True) parentId = models.IntegerField() keyText = models.CharField(max_length=200) class RuletreeExtended(models.Model): rule = models.OneToOneField(RuleTree,on_delete=models.CASCADE,primary_key=True) createdOnUtc = models.TextField(blank=True) bodyRegion = models.CharField(blank=True,max_length=100) isActive = models.BooleanField(blank=True) I need to design an API with the following structured inputs and save them to the pre-defined database model (there are several more fields in this input structure that need to access from views.py and will be useful later). { "Success": true, "Status": "insert", "Data": { "RuleJson": "{\"condition\":\"AND\",\"rules\":[{\"condition\":\"OR\",\"rules\":[{\"id\":\"1206\",\"field\":\"ansid_1206\",\"type\":\"integer\",\"input\":\"checkbox\",\"operator\":\"in\",\"value\":[2620,2621,2622]},{\"id\":\"1383\",\"field\":\"ansid_1383\",\"type\":\"integer\",\"input\":\"checkbox\",\"operator\":\"in\",\"value\":[3058,3059,3060,3061,3062,3063,3064,3065,3066,3067]}]}],\"valid\":true}", "ICD10Codes": "3916", "CreatedOnUtc": "2021-11-01T10:33:13.7145563", "UpdatedOnUtc": "2021-11-09T13:04:01.3089361", "BodyRegion": [ 0, 1, 5 ], "IsDefaultBodyRegionRule": false, "DefaultBodyRegionList": [ 0, 4 ], "IsActive": false, "IsDeleted": false, "Id": 5504, "ParentId": 276, "KeyText": "PFRProv1", "Title": "Plantar Fasciitis Right" } } Please advise me how to access this input data from views.py so that I can store them in my database; And how do I design a suitable serializer for this. -
Django display several foreign key values in template
I have tried dozens of solutions on her to solve this but nothing seems to be working as expected. I'm trying to show a list of Facilites which are connected with several Foreign Keys to additonal models. (FacilityAddress, FacilityInspectionInfo and FacilityComplaints). I can show the facility names but i cannot show the data of the models within the foreign key models like FacilityAddress for example: Model class Facility(models.Model): UUID = models.CharField(max_length=150, null=True, blank=True) Name = models.CharField(max_length=50, null=True, blank=True) admin_uid = models.OneToOneField(User, null=True, blank=True, on_delete=models.SET_NULL) IssuedNumber = models.CharField(max_length=20, null=True, blank=True) mainimage = models.ImageField(null=True, blank=True) Capacity = models.IntegerField(null=True, blank=True) Licensee = models.CharField(max_length=50, null=True, blank=True) Email = models.EmailField(max_length=30, null=True, blank=True) AdministratorName = models.CharField(max_length=30, null=True, blank=True) Status = models.CharField(max_length=10, null=True, blank=True) TelephoneNumber = models.CharField(max_length=20, null=True, blank=True) ClosedTimestamp = models.IntegerField(null=True, blank=True) MostRecentLicenseTimestamp = models.IntegerField(null=True, blank=True) class Meta: verbose_name_plural = "facilities" def __str__(self): return self.Name class FacilityAddress(models.Model): PrimaryAddress = models.CharField(max_length=50, null=True, blank=True) SecondaryAddress = models.CharField(max_length=50, null=True, blank=True) City = models.CharField(max_length=50, null=True, blank=True) RegionOrState = models.CharField(max_length=30, null=True, blank=True) PostalCode = models.CharField(max_length=20, null=True, blank=True) Geolocation = models.CharField(max_length=20, null=True, blank=True) AddressInfo = models.ForeignKey(Facility, null=True, blank=True, on_delete=models.CASCADE) class Meta: verbose_name_plural = "facility addresses" def __str__(self): return f"{self.PrimaryAddress} {self.City}" class FacilityInspectionInfo(models.Model): ComplaintRelatedVisits = models.IntegerField(null=True, blank=True) InspectionRelatedVisits = models.IntegerField(null=True, blank=True) NumberOfVisits = … -
CommandError: 'D:\Python\Project\resume_1' already exists
I am creating a django project. I can successfully create virtual environment and pip install django, but when I try to create project using django-admin startproject resume_1 There is an error that showed CommandError: 'D:\Python\Project\resume_1' already exists I tried uninstalling django twice but it only allowed me to uninstall once, so it is likely not about duplicate django, I also checked the lib\site-packages, there are no duplicated folders or folders either. However, I do have two versions of python right now, one installed along with anaconda, one is separated from anaconda and directly downloaded from python.org. Right now, I am just using the separate python, I even checked the python version, and the pip version, so it should be fine. Still, I could be wrong since I am not that experienced. What should I do? -
How can i fully customize sidebar_menu in django admin panel?
I don't know any way how can I overright sidebar_menu.html or create some progress to customize it. so can i get some hits what can i do for coustomize? -
Converting SQL to something that Django can use
I am working on converting some relatively complex SQL into something that Django can play with. I am trying not to just use the raw SQL, since I think playing with the standard Django toolkit will help me learn more about Django. I have already managed to break up parts of the sql into chunks, and am tackling them piecemeal to make things a little easier. Here is the SQL in question: SELECT i.year, i.brand, i.desc, i.colour, i.size, i.mpn, i.url, COALESCE(DATE_FORMAT(i_eta.eta, '%M %Y'),'Unknown') as eta FROM i JOIN i_eta ON i_eta.mpn = i.mpn WHERE category LIKE 'kids' ORDER BY i.brand, i.desc, i.colour, FIELD(size, 'xxl','xl','l','ml','m','s','xs','xxs') DESC, size+0, size Here is what I have (trying to convert line by line): (grabbed automatically when performing filters) (have to figure out django doc on coalesce for syntax) db alias haven't been able to find yet - it is crucial since there is a db view that requires it already included in the original q .select_related? .filter(category="kids") .objects.order_by('brand','desc','colour') - don't know how to deal with SQL FIELDS Any advice would be appreciated! -
Gunicorn Not Finding Dotenv
I'm in the process of setting up a Digital Ocean Ubuntu VPS with Django following the instructions they supplied. I was able to run: python3 manage.py runserver 0.0.0.0:8000 The application came up and worked. It's a copy from my development machine. The next step is to test Gunicorn. The command given is: gunicorn --bind 0.0.0.0:8000 fosteryouth.wsgi The process exits with the last of the error messages being: File "/var/www/fosteryouth/fosteryouth/settings.py", line 15, in <module> from dotenv import load_dotenv ModuleNotFoundError: No module named 'dotenv' [2021-12-19 00:43:51 +0000] [59490] [INFO] Worker exiting (pid: 59490) [2021-12-19 00:43:51 +0000] [59488] [INFO] Shutting down: Master [2021-12-19 00:43:51 +0000] [59488] [INFO] Reason: Worker failed to boot. The first non-comment lines from my setting file are: from pathlib import Path import os from dotenv import load_dotenv load_dotenv(override=True) Line 15 is "from dotenv import load_dotenv" There was no problem finding it when using runserver above. I'm using virtualenv and it is activated. I've set up number other Django servers on Digital Ocean in the past. At the time, the instructions didn't include this step. You went directly the setting up socket and services files for gunicorn. Any idea what the problem is? Ubuntu 20.04, Django 4.0, Python 3.8 -
Run tests on Heroku Docker container with GitHub Actions
I am successfully deploying to Heroku a dockerized Django app via GitHub Actions. My GitHub Actions workflow: name: Deploy to heroku. on: push: branches: [poet] jobs: build: runs-on: ubuntu-latest steps: # Check-out your repository. - name: Checkout uses: actions/checkout@v2 # Build and deploy - name: Build, push, and release Docker to Heroku. uses: gonuit/heroku-docker-deploy@v1.3.3 with: email: <email> heroku_api_key: ${{ secrets.HEROKU_API_KEY }} heroku_app_name: <app> dockerfile_directory: ./image/app/ dockerfile_name: Dockerfile docker_options: "--no-cache --target prod" process_type: web - name: Test run: python manage.py test # this doesn't work First of all, I'd like to confirm that the test step should be something like what I show above (name: Test). In other words, should testing be another step in the build job? Or should it be it's own job? Running that command as a step within the same job produces the error python: can't open file 'manage.py'. Alternatively, if I were to make it its own job, I suppose I should try with heroku ps:exec. However, to interact with a Docker container in Heroku apparently requires a lot of modifications and I'm not convinced that's the way to go yet. For what it's worth, if I try to run the console in Heroku and in … -
How to unhash a password in Django if you know the Secret Key
I have a simple Django website setup. For a science fair project, i am showing vulnerabilities in Django. I know the secret key of the website, and I have a hashed password. How can I unhash the password using the Secret Key? Also if anyone can do it for me - Here is the hashed password: pbkdf2_sha256$260000$zWIVM50moQjtqcPoX5Fycd$X7Dq6BKX5lHiY9dnBlBdR3OGrJuREX5uSeCSbA4ZdaE= And here is the secret key: django-insecure-vv7oicn&(hj10ds11-b*nus#b%h=xqzyhr&b$&g9+_1gmckd$2 If anyone can unhash it for me, I can paypal you some money, I really need this done. Thanks! -
Summing columns in Django with related fields
I'm trying to do some aggregation on some of my Django columns, but I'm getting an error I can't figure out. Here are my models (the relevant stuff anyways): class Fillup(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) date = models.DateField(default=date.today) trip_distance = models.FloatField(validators=[MinValueValidator(0.0)]) car = models.ForeignKey('Car',on_delete=models.CASCADE, related_name='fillups') class Car(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) name = models.CharField(max_length=25) So each Fillup object is essentially a tank of gas in a car, and what I want to do is get the total of the trip_distance column for each car. I've tried several things from various other StackOverFlow pages, but nothing seems to work. My first attempt was this adding this field to the Car Model: @property def distance_driven(self): return self.fillups.aggregate(sum('trip__distance')) But I just get the following error: TypeError: unsupported operand type(s) for +: 'int' and 'str' I also tried adding this to my serializer, but got the same error: distance_driven = serializers.SerializerMethodField() def get_distance_driven(self, ob): return ob.fillups.all().aggregate(sum('trip_distance'))['trip__distance'] Is there something I'm missing here? I don't understand why I'm getting that error when trying to sum a FloatField column. Any help would be greatly appreciated! -
How can I decrypt a Django password?
I have a simple website set up with Django, and I want to know how I can decrypt a password in order to access the Django Admin panel. Assuming I know the username, is it possible to decrypt the password so that I can access the account? Also here is the encryption if anyone wants to help: pbkdf2_sha256$260000$zWIVM50moQjtqcPoX5Fycd$X7Dq6BKX5lHiY9dnBlBdR3OGrJuREX5uSeCSbA4ZdaE= -
Why postgres changes the order after updating record django postgres
I'm updating a record in my Postgres database but I don't know why after updating the record Postgres changes the order of the updated row in the DB, I have attached the example below. views.py @api_view(['GET', 'PATCH']) def tag_detail(request, project_id, tag_id): if request.method == 'PATCH': tag = Tag.objects.get(project_id=project_id, pk=tag_id) tag.ship_date = request.data.get('ship_date', tag.ship_date) tag.save() return Response("ok") before update order: Record 1 Record 2 Record 3 let's assume we have updated "Record 2", so the order will be: Record 1 Record 3 Record 2 -
Sudden trouble connecting to consumer using Celery and CloudAMQP. Error message: BDB0210 celerybeat-schedule.db: metadata page checksum error
I am using CloudAMQP with Celery on Heroku to schedule tasks. When I push my code to Heroku, I am suddenly receiving the following error: BDB0210 celerybeat-schedule.db: metadata page checksum error consumer: Cannot connect to amqps://user:password@bonobo.rmq.cloudamqp.com:port/user: The read operation timed out. The thing is, it worked perfecty fine for like 3 months. The other day I'm suddenly getting this error. I've check the commits on Github, and there have been no adjustments to my settings. What could this error be then? My current Heroku configurations are: CELERY_BROKER_URL = "amqps://user:password@bonobo.rmq.cloudamqp.com:port/user" CELERY_RESULT_BACKEND = "rpc://" CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' My Procfile reads: web: gunicorn project_settings.wsgi --log-file - worker: celery -A project_settings worker --beat -
Archive records and re-inserting new records in Django?
I've got a Stock table and a StockArchive table. My Stock table consists of roughly that 10000 stocks that I update daily. The reason I have a StockArchive table is because I still wanna some historic data and not just update existing records. My question is, is this a proper way of doing it? First, my models: class Stock(models.Model): objects = BulkUpdateOrCreateQuerySet.as_manager() stock = models.CharField(max_length=200) ticker = models.CharField(max_length=200) exchange = models.ForeignKey(Exchange, on_delete=models.DO_NOTHING) eod_price = models.DecimalField(max_digits=12, decimal_places=4) currency = models.CharField(max_length=20, blank=True, null=True) last_modified = models.DateTimeField(blank=True, null=True) class Meta: db_table = "stock" class StockArchive(models.Model): objects = BulkUpdateOrCreateQuerySet.as_manager() stock = models.ForeignKey(Stock, on_delete=models.DO_NOTHING) eod_price = models.DecimalField(max_digits=12, decimal_places=4) archive_date = models.DateField() class Meta: db_table = "stock_archive" I proceed on doing the following: @transaction.atomic def my_func(): archive_stocks = [] batch_size = 100 old_stocks = Stock.objects.all() for stock in old_stocks: archive_stocks.append( StockArchive( stock=stock.stock, eod_price = stock.eod_price, archive_date = date.today(), ) ) # insert into stock archive table StockArchive.objects.bulk_create(archive_stocks, batch_size) # delete stock table Stock.objects.all().delete() # proceed to bulk_insert new stocks I also wrapped the function with a @transaction.atomic to make sure that everything is committed and not just one of the transactions. Is my thought process correct, or should I do something differently? Perhaps more efficient? -
Reverse for 'new-quiz' with arguments '(11, '')' not found. 1 pattern(s) tried: ['course/(?P<course_id>[^/]+)/(?P<module_id>[^/]+)/quiz/newquiz$']
here is my code views.py from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from django.http import HttpResponseForbidden from quiz.forms import NewQuizForm, NewQuestionForm from quiz.models import Answer, Question, Quizzes, Attempter, Attempt from courses.models import Module from completion.models import Completion # Create your views here. def NewQuiz(request, course_id, module_id): user = request.user module = get_object_or_404(Module, id=module_id) if request.method == 'POST': form = NewQuizForm(request.POST) if form.is_valid(): title = form.cleaned_data.get('title') description = form.cleaned_data.get('description') due = form.cleaned_data.get('due') allowed_attempts = form.cleaned_data.get('allowed_attempts') time_limit_mins = form.cleaned_data.get('time_limit_mins') quiz = Quizzes.objects.create(user=user, title=title, description=description, due=due, allowed_attempts=allowed_attempts, time_limit_mins=time_limit_mins) module.quizzes.add(quiz) module.save() return redirect('new-question', course_id=course_id, module_id=module_id, quiz_id=quiz.id) else: form = NewQuizForm() context = { 'form': form, } return render(request, 'quiz/newquiz.html', context) def NewQuestion(request, course_id, module_id, quiz_id): user = request.user quiz = get_object_or_404(Quizzes, id=quiz_id) if request.method == 'POST': form = NewQuestionForm(request.POST) if form.is_valid(): question_text = form.cleaned_data.get('question_text') points = form.cleaned_data.get('points') answer_text = request.POST.getlist('answer_text') is_correct = request.POST.getlist('is_correct') question = Question.objects.create(question_text=question_text, user=user, points=points) for a, c in zip(answer_text, is_correct): answer = Answer.objects.create(answer_text=a, is_correct=c, user=user) question.answers.add(answer) question.save() quiz.questions.add(question) quiz.save() return redirect('new-question', course_id=course_id, module_id=module_id, quiz_id=quiz.id) else: form = NewQuestionForm() context = { 'form': form, } return render(request, 'quiz/newquestion.html', context) def QuizDetail(request, course_id, module_id, quiz_id): user = request.user quiz = get_object_or_404(Quizzes, id=quiz_id) my_attempts = Attempter.objects.filter(quiz=quiz, user=user) context = { … -
Django smart selects chain 2 models with country list that is not its own model
I have 3 models CompanyRole, Office and extended user model - and have successfully implemented django smart selects package and have created a ChainedForeignKey select from Office to CompanyRole. CompanyRole model having records employee and freelance and Office model having the office name and companyrole field for employee only - this works as expected as in dropdown for companyrole user selects employee then in dropdown for offcies will be populated but if freelance selected from company role dropdown then nothing will be populated in office dropdown. However, I also have a field in user model called location and country field in office model which populates a country list from django_countries package so did not have to create a model for countries. Please see my models.py file below: models.py from django.db import models from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from django_countries.fields import CountryField from smart_selects.db_fields import ChainedForeignKey class CompanyRole(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class Office(models.Model): company_role = models.ForeignKey(CompanyRole, on_delete=models.CASCADE) country = CountryField(null=True) name = models.CharField(max_length=30) def __str__(self): return self.name class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) username = models.CharField(max_length=150, unique=True) first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) start_date = models.DateTimeField(default=timezone.now) comments = … -
Django sum of a particular field for some distinct column
I have a table OrderTransaction which has foreign key for table Order. I want to calculate the outstanding amount i.e. the amount for which transaction has not yet occurred. To calculate that I first need to calculate the total amount (Order table has field total amount) so that I can subtract the amount of transaction that has taken place from it. I am grouping by the the query by recorded_by field because I need to know what salesman has collected how much amount. Following is my query. order_transaction_qs .exclude(recorded_by=None) .order_by("recorded_by") .values("recorded_by") .annotate( cash_in_hand=Coalesce( Sum("amount", filter=Q(payment_method=PaymentMethod.CASH_ON_DELIVERY)), Value(0) ), cheque=Coalesce( Sum("amount", filter=Q(payment_method=PaymentMethod.CHEQUE)), Value(0) ), others=Coalesce( Sum( "amount", filter=~Q( payment_method__in=[ PaymentMethod.CHEQUE, PaymentMethod.CASH_ON_DELIVERY, ] ), ), Value(0), ), order_amount=Sum( "order__total_amount" ), # NOTE: Multiple transactions on same orders will give extra amount. outstanding=ExpressionWrapper( F("order_amount") - (F("cash_in_hand") + F("cheque") + F("others")), output_field=FloatField(), ), ) The problem with above query is that if there are multiple transaction for same order, it is adding the total_amount multiple times. Please suggest me what to do. -
'QuerySet' object has no attribute 'pesel'
I'm new with django. I'm really confused with views. Here is my models.py class Pacjent(models.Model): name= models.CharField(max_length=30) surname = models.CharField(max_length=30) pesel = models.ForeignKey(Pesel, on_delete=models.CASCADE) birth = models.DateField(datetime.date) Here is my views.py: def pacjent_view(request): obj =Pacjent.objects.all() context={'pesele': obj.pesel} return render(request,'PrzychodniaZdrowia/kartapacjenta.html',context) An error is displayed when trying to start: "Exception Value: 'QuerySet' object has no attribute 'pesel'". What is wrong with this code? How do I display this model on the website? -
Why am I getting a Django Type Error when using Taggit?
So I am following a digital book on how to add tags to Django using Taggit. The List page is also using Paginator, but what is happening is I am getting this Type Error when I click on one of the tags which is supposed to take you to keep you on the list page, but list the number of posts with the same tag. Please let me know if you need more information from me. I really appreciate all of your help. I'm excited because this is my first real Django project, creating a blog for a friend and so far things are coming along well except for this one issue that is beyond me. I also want to learn how to be able to look at error screens and know what to look for and then how to solve my own issues one day. Thanks again! Chris This is the Error Screen Shot views.py from django.shortcuts import render, redirect, get_object_or_404 from django.views.generic import ListView from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.db.models import Count from taggit.models import Tag from .models import Post from .forms import PostForm class PostListView(ListView): queryset = Post.published.all() context_object_name = 'posts' paginate_by = 3 template_name … -
Django filter results on foreign key
I am attempting to display a list of notes that are attached to a project. I can display the individual project the notes are linked to but I am not able to figure out how to display only the notes related to the project. My models are: class Project(models.Model): title = models.CharField(max_length= 200) description = models.TextField() def __str__(self): return self.title class ProjectNotes(models.Model): title = models.CharField(max_length=200) body = models.TextField() date = models.DateField(auto_now_add=True) project = models.ForeignKey(Project, default=0, blank=True, on_delete=models.CASCADE, related_name='notes') def __str__(self): return self.title The views: from django.shortcuts import get_object_or_404, render from django.urls.base import reverse from django.views.generic import ListView, DetailView from django.views.generic.edit import CreateView from .models import Project, ProjectNotes class CompanyProjects(ListView): model = Project template_name = 'company_accounts/projects.html' class CompanyProjectsDetailView(DetailView): model = Project id = Project.objects.only('id') template_name = 'company_accounts/project_detail.html' context_object_name = 'project' class ProjectNotes(ListView): model = ProjectNotes template_name = 'company_accounts/project_notes.html' def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) context['project'] = get_object_or_404(Project, id=self.kwargs.get('pk')) return context class ProjectNotesDetailview(DetailView): model = ProjectNotes template_name = 'company_accounts/project_note_detail.html' The template displays the correct project: {% extends 'base.html' %} {% block content %} <h1>Notes</h1> {{ project }} {% for note in notes %} <div class ="projectnotes-entry"> <h2><a href="">{{ note.title }}</a></h2> <p>{{ note.body … -
How do I link a Django foreign key selected in a form with an inline form?
Introduction Hello! I am a self-taught novice python/Django coder working on my family business truck maintenance Django app. I have some of the basics of Django and python3 down, but other basics escape me as everything I am learning has been done for practicality sake and not built from the foundations of these languages. I have the following types of models: Truck - a single truck Service - a single instance of a repair/maintenance service for a single truck Photo - a single picture from the photologue app PhotoExtended - an add-on model one-to-one with Photo where it can be linked to a truck and/or a service. A photo will ALWAYS be associated with a truck, but may or may not be associated with a service. relevant models.py: class PhotoExtended(models.Model): # Link back to Photologue's Photo model. photo = models.OneToOneField(Photo, related_name='extended', on_delete=models.RESTRICT) truck = models.ForeignKey('Truck', on_delete=models.CASCADE, default = DEFAULT_TRUCK_ID, help_text="Truck in the picture.") service = models.ForeignKey('Service', on_delete=models.PROTECT, null=True, blank=True, help_text="Service being performed or finished in the picture.") receipt = models.BooleanField(help_text="Is the picture for a receipt?", null=True, default=False) # Boilerplate code to make a prettier display in the admin interface. class Meta: verbose_name = u'Associated photo' verbose_name_plural = u'Associated photos' def … -
Why i get an error in django host.py file?
from django.conf import settings from django_hosts import patterns, host host_patterns = patterns('', host(r'www',settings.ROOT_URLCONF, name='www'), ) And when it runs it brings:: Traceback (most recent call last): File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in start(fakepyfile,mainpyfile) File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start exec(open(mainpyfile).read(), main.dict) File "", line 7, in File "/data/user/0/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.9/site-packages/django/conf/init.py", line 56, in getattr self._setup(name) File "/data/user/0/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.9/site-packages/django/conf/init.py", line 37, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting ROOT_URLCONF, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. [Program finished] -
Git Hub we don't support that file type
I am trying to add some django project files to my github repository but for some reason github keeps saying it doesn't support the file types of my project