Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse for 'download_report' with arguments '()' and keyword arguments '{u'regid': 75}' not found. 0 pattern(s) tried: []
I'm new to django. I want to extend the existing project. I want to display dynamic data table and download report of a particular id. When I run the project it returns Reverse for 'download_report' with arguments '()' and keyword arguments '{u'regid': 75}' not found. 0 pattern(s) tried: [] urls.py > url(r'^(?P<regid>\d+)/$', > views.ApplicationView.as_view(),name="view_application"), registrationlist.html <li> <a href="{% url 'download_report' regid=registrationid %}"><span class="glyphicon glyphicon-list-alt"></span> Download Report</a> </li> views from random import shuffle from constance import config from django.contrib.auth.mixins import LoginRequiredMixin from django.shortcuts import render # from django.template.response import SimpleTemplateResponse from django.views import View from bps_registration.models import NewRegistration def get_related_object_or_none(related_manager): try: return related_manager.get() except: return None class DownloadReport(LoginRequiredMixin, View): def get(self, request, regid): context = {} context['municipality'] = config.Municipality context['registrationid'] = regid reg = NewRegistration.objects.get(id=regid) context['registration'] = reg context['application_status'] = reg.applicationstatus_set.all() context['application'] = get_related_object_or_none(reg.application_set) context['houseowner'] = reg.houseownerinfo_set.all() houseowner_names = ", ".join(reg.getAllHouseownerNpNameAsList()) if houseowner_names == "": context['houseowner_name'] = u"{} ({})".format(reg.houseowner_name_np, reg.houseowner_name_en) else: context['houseowner_name'] = houseowner_names context['landowner'] = reg.landowner_set.all() context['applicant'] = get_related_object_or_none(reg.applicant_set) context['landinformation'] = get_related_object_or_none(reg.landinformation_set) charkillas = reg.charkilla_set.all() for ch in charkillas: if ch.ch_direction == "n": context['charkilla_n'] = ch elif ch.ch_direction == "e": context['charkilla_e'] = ch elif ch.ch_direction == "s": context['charkilla_s'] = ch elif ch.ch_direction == "w": context['charkilla_w'] = ch else: context['charkilla_other'] = β¦ -
Django UpdateView misses queryset
I can't figure out, what is wrong with my code. I tried so much stuff and my createview is working. But there I use the flight and not the gatehandling as pk. For me this seems okay, and I dont understand why the console tells me that querysets are missing. models.py class Airport(models.Model): name = models.CharField(max_length=255, unique=True) class Flight(models.Model): start = models.ForeignKey(Airport, on_delete=models.CASCADE, related_name='start') end = models.ForeignKey(Airport, on_delete=models.CASCADE, related_name='end') number = models.CharField(max_length=5, default="EJT12") class Gate(models.Model): airport = models.ForeignKey(Airport, on_delete=models.CASCADE) number = models.IntegerField(default=0) class GateHandling(models.Model): gate = models.ForeignKey(Gate, on_delete=models.CASCADE) flight = models.ForeignKey(Flight, on_delete=models.CASCADE) urls.py path('gate-handling/<int:pk>/update', views.GateHandlingUpdate.as_view(), name='gate_handling_update'), detail.html {% for flight in flights_arriving %} {% for gate_handling in flight.gatehandling_set.all %} <p>{{gate_handling}} <a href="{% url 'management:gate_handling_update' gate_handling.pk %}">Change</a></p> {% empty %} <p>Gate <a href="{% url 'management:gate_handling_create' flight.pk %}">Assign</a></p> {% endfor %} {% endfor %} views.py class GateHandlingUpdate(UpdateView): form_class = GateHandlingUpdateForm template_name = 'management/gatehandling_update.html' def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['airport'] = Gate.objects.get(gatehandling=self.object).airport kwargs['flight'] = Flight.objects.get(pk=self.object.flight.pk) return kwargs forms.py class GateHandlingUpdateForm(ModelForm): class Meta: model = GateHandling fields = ['gate', 'flight'] def __init__(self, *args, **kwargs): airport = kwargs.pop('airport') flight = kwargs.pop('flight') super().__init__(*args, **kwargs) self.fields['flight'].queryset = Flight.objects.filter(pk=flight.pk) self.fields['gate'].queryset = Gate.objects.filter(airport=airport) console Internal Server Error: /gate-handling/9/update Traceback (most recent call last): File "D:\airport\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner β¦ -
How to run python project in context of Django
I'm working on a Python project, I finished it and I decided to turn it into SaaS (software as service) by using the Django framework (REST API) for the backend and VueJs for the frontend. For the part of the django + Vuejs I did things well. the problem is that I do not know how to integrate my python project that runs on linux with Django. image describe my work (how to import it, how to install the requirements, how to change the parameters with the interface Vuejs ...) Do I have to run my Python project in a server and control it with django? If yes, how ? I do not know if this approach is the best to launch a Saas? thank you for helping me to have a global idea about how things work. -
How to get object wise keys in Django requests?
I'm creating an Custom Object which has user as Foreign Key, so the request I'm getting is in the form: <QueryDict: {'csrfmiddlewaretoken': ['someToken'], 'name': ['SomeName'], 'user.username': ['username'], 'user.email': ['email@gmail.com'], 'user.password': ['1234']}> I need to get all attributes with keys starting from user.. Basically, it's my User object in that request. Is there any way to get it directly instead of nitpicking every key-val pair? Thanks -
Django: AttributeError: 'AdminSite' object has no attribute 'reqister'
So I am starting with Django and I am working on the Django tutorial-project, that includes a poll application. The tutorial gave me the Code: from django.contrib import admin from .models import Question admin.site.register(Question) But when I add this to my code and try it out it gives me the error: AttributeError: 'AdminSite' object has no attribute 'reqister' My admin.py file looks exactly like this and without this code everything is running fine -
Deploying a Django Project through Git to Heroku: "No module named.. - failure"
I'm hoping you may be able to help me and at the same time, I hope this query may serve others here well in the future. Based on the excellent book: Python Crash Course by Eric Matthes, I am trying to deploy a Django app to Heroku with the use of Git and have come across several issues. Do note, there are some corrections to the book here: https://ehmatthes.github.io/pcc/updates.html I am specifically mentioning the book here, as I believe it to be ranked one of the best starter books on various sites, so I can imagine other people facing the same problems - also, as there are several posts related to these 3 topics. Initially, the app could be commited to Git, but then not pushed to Heroku using: git push heroku master Part 1: This contineously brought about the error: No Procfile and no package.json file found in Current Directory - See heroku local --help To resolve this, it was vital to make sure the file had no extension (mac os) did not show it, but an ls in the directory showed the .txt ending on the file. Part 2: Retrying this, now allowed for a new message: ModuleNotFoundError: β¦ -
How to implement m2m_changed in django?
Basically, my question is how do I implement the m2m_changed so that when I am creating, updating or deleting an instance of ClassSubjectGrade, the intermediate table between ClassSubjectGrade and Student is also updated. Example: 1. Adding more students when I edit an instance of ClassSubjectGrade will add those students associated to the intermediate table 2. Removing students from an instance of ClassSubjectGrade will remove those students associated from the intermediate table 3. Deleting an instance of ClassSubjectGrade will remove all students associated with that instance I placed my code below but I am not sure as well if I should check for those 2 actions or there is a simple way to do it. I do not get in the documentation as well how to write the code to do the things that I want whenever I am doing the 3 examples above. class Student(models.Model): # some fields class ClassSubjectGrade(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE) # other fields students = models.ManyToManyField(Student, blank=True) from django.db.models.signals import m2m_changed @receiver(m2m_changed, sender=ClassSubjectGrade.students.through) def students_changed(sender, instance, action, **kwargs): if action == 'post_remove': # How to remove all instances in intermediate table of # ClassSubjectGrade and Student # of all students that were removed from a ClassSubjectGrade β¦ -
how to take 'X' number of inputs in django form
First of all, I have looked at other similar questions and none of them answer my question so that is why I am posting a separate question. Now, coming to problem, let me first describe what i have to do and then i will explain the problem. I have to make 2 pages, 1st will take 3 inputs: that will be 3 numbers and those numbers will represent the number of fields fr each field in the next page. and when user goes to next page, that number of fields will appear. For example, at first page I give the input 2,3,2 then at the next page a total of 7(2+3+2) input boxes will appear and then whatever user inputs in those have to be stored in my model(database). I cant make multiple forms and multiple views (for 2nd page) and then call the appropriate according to the needs because catering every possible combination of input of first page will be too much inefficient. I dont want to use angular or ajax. I am using Form not ModelForm I have read about how to make variable number of fields using init function of forms.py and I have also read So β¦ -
How to pass choices in template using dropdown html fields? (Django)
These are my files, Views.py Forms.py Models.py Html template Whenever I save the instance, it saves the type as "option value=" in type column. How do I pass type in database properly? -
Django Machine learning: '<' not supported between instances of 'Applicant' and 'Applicant'
I have a model that I want to use for predictions which I have loaded using pickle and I have a form created in using django. But when a user submits the form I want it to be in store it in a csv format in a variable so I can perform Xgboost prediction on every form the user fills and after it outputs the prediction. COuld it be its not getting any input. New to this from django.db import models from django import forms from django.core.validators import MaxValueValidator, MinValueValidator # Create your models here. type_loan=(("Cash loan","Cash loan"), ("Revolving loan","Revolving Loan")) Gender=(("Male","Male"), ("Female","Female")) Yes_NO=(("YES","YES"),("NO","NO")) status=(("Single","Single"), ("Married","Married"), ("Widow","Widow"), ("Seprated","Divorce")) Highest_Education=(("Secondary","Secondary"), ("Incomplete Higher","Incomplete Higher"), ("Lower Secondary","Lower Secondary"), ("Academic Degree","Academic Degree")) Income_type=(("Working","Working Class"), ("State Servant","Civil Servant"), ("Commercial Associate","Commercial Associate"), ("Pensioner","Pensioner"), ("Student","Student"), ("Businessman","Business Owner")) class Applicant(models.Model): name=models.CharField(default="Jon Samuel",max_length=50,null="True") Birth_date=models.DateField(default="2018-03-12",blank=False, null=True) Status=models.CharField(choices=status,max_length=50) Children=models.IntegerField(default=0,validators=[MinValueValidator(0),MaxValueValidator(17)]) Highest_Education=models.CharField(choices=Highest_Education,max_length=50) Gender=models.CharField(choices=Gender, max_length=50) loan_type=models.CharField(choices=type_loan, max_length=50) own_a_car=models.CharField(choices=Yes_NO,max_length=50) own_a_house=models.CharField(choices=Yes_NO,max_length=50) def __str__(self): return self.name views.py from django.shortcuts import render from .models import Applicant from .forms import Applicant_form from django.views.generic import ListView, CreateView, UpdateView from django.core.cache import cache import xgboost as xgb import pickle from sklearn.preprocessing import LabelEncoder class CreateMyModelView(CreateView): model = Applicant form_class = Applicant_form template_name = 'loan/index.html' success_url = '/loan/results' context_object_name = 'name' class β¦ -
need to restrict relationship using foreign key
I need that when registering a Pessoa and a Veiculo they are realacionamos in a way that when registering using Views Mensalista when I put Pessoa soment the Veiculo that is owned by it appears Models.py STATE_CHOICES = ( ('AC', 'Acre'), ('AL', 'Alagoas'), ('AP', 'AmapΓ‘'), ('AM', 'Amazonas'), ('BA', 'Bahia'), ('CE', 'CearΓ‘'), ('DF', 'Distrito Federal'), ('ES', 'EspΓrito Santo'), ('GO', 'GoiΓ‘s'), ('MA', 'MaranhΓ£o'), ('MT', 'Mato Grosso'), ('MS', 'Mato Grosso do Sul'), ('MG', 'Minas Gerais'), ('PA', 'ParΓ‘'), ('PB', 'ParaΓba'), ('PR', 'ParanΓ‘'), ('PE', 'Pernambuco'), ('PI', 'PiauΓ'), ('RJ', 'Rio de Janeiro'), ('RN', 'Rio Grande do Norte'), ('RS', 'Rio Grande do Sul'), ('RO', 'RondΓ΄nia'), ('RR', 'Roraima'), ('SC', 'Santa Catarina'), ('SP', 'SΓ£o Paulo'), ('SE', 'Sergipe'), ('TO', 'Tocantins') ) class Pessoa(models.Model): nome = models.CharField(max_length=50, blank=False) email = models.EmailField(blank=False) cpf = models.CharField(max_length=11, unique=True, blank=False) endereco = models.CharField(max_length=50) numero = models.CharField(max_length=10) bairro = models.CharField(max_length=30) telefone = models.CharField(max_length=20, blank=False) cidade = models.CharField(max_length=20) estado = models.CharField(max_length=2, choices=STATE_CHOICES) def __str__(self): return str(self.nome) + ' - ' + str(self.email) class Veiculo(models.Model): marca = models.ForeignKey(Marca, on_delete=models.CASCADE, blank=False) modelo = models.CharField(max_length=20, blank=False) ano = models.CharField(max_length=7) placa = models.CharField(max_length=7) proprietario = models.ForeignKey( Pessoa, on_delete=models.CASCADE, blank=False, ) cor = models.CharField(max_length=15, blank=False) def __str__(self): return self.modelo + ' - ' + self.placa views.py @login_required def mensalista_novo(request): if request.method == β¦ -
Before and after login, I want to use same URL but use different class based view
Before and after user login, URL is not changed in many websites. How should I implement this in Django? For example, http://example.com (show login page) β login β http://example.com (show content list) I want to use class based view for Login Page (auth_views.LoginView), then after user login, use generic list View and different template. urls.py from django.contrib.auth import views as auth_views urlpatterns = [ path('', auth_views.LoginView.as_view(template_name='index.html'), name='index'), views.py from django.views.generic import ListView class UserIndexView(ListView): model = mymodel template_name = 'user_index.html' -
How to set a backend in django auth LoginView in urls.py
As I am using social_auth as well, how can I set the auth backend to LoginView? urls.py path('login/', django.contrib.auth.views.LoginView.as_view ( template_name='login.html', ), name='login'), settings.py AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'social_core.backends.linkedin.LinkedinOAuth2', ) Some say that if the auth ModelBackend is before the social auth, it will go through it, somehow this is not working out. -
add custom action button in django admin
Now I'm working on deleting files from s3 at django admin page. I would like to delete files in s3 when I click 'remove' button that I added as a custom button. The 'remove' button is located next to file download link at django admin front page as shown in the following link (image): custom UI screenshot (step 1) When I click the 'remove' button, (step 2) I want to make the front-end admin page to send a request to the back-end web server which uses boto3 library. (step 3) Once the request arrives at the back-end, I want the boto3 to communicate with S3 so that the requested file is deleted in S3 side. (step 4) Then, S3 should respond to the boto3 back, saying the requested delete operation is done. To achieve these steps, I think I need to define/implement an interface in the web-server side and make the listener on the 'remove' button to send a request to the web-server side interface I created. However, I can't find a way to do so. Any suggestions or documentations that I can get some help on this issue? Here I give you the corresponding code section of admin.py file. β¦ -
Using multiple slugs in urls.py
I'm trying to use two slugs in my urls but I keep getting Reverse for 'tithe' with arguments '(2018, 'February')' not found. 1 pattern(s) tried: ['tithe/(?P<year>[0-9]{4})-(?P<month>[\\w-])/$']. urls.py `from django.contrib import admin from django.urls import path,include,re_path from django.conf.urls import url from tithe import views from django.views.generic import RedirectView from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('', RedirectView.as_view(pattern_name="account_login"), name="index"), path('accounts/', include('allauth.urls')), path('dashboard', views.Dashboard.as_view(), name='dashboard'), url(r'^tithe/(?P<year>[0-9]{4})-(?P<month>[\w-])/$',views.TitheView.as_view(), name='tithe'), ]` dashboard.html <a href="{% url 'tithe' currentYear realMonth %}" class="waves-effect"><i class="zmdi zmdi-format-underlined"></i> <span> Tithe </span> </a> -
django: search by ingredients
I'm creating a site where users can search for recipes for ingredients, but I can only search by typing 1 ingredient, when I type more than one, the search returns empty. The right search would be the user to insert multiple ingredients and return the recipes that contain those ingredients. I cannot find what's wrong :( Here are my models.py class Fotos(models.Model): id = models.AutoField(primary_key=True) linkfoto = models.ImageField() nomes = models.ForeignKey('Nomes', models.DO_NOTHING, blank=True, null=True) class Meta: managed = False db_table = 'fotos' class Ingredientes(models.Model): id = models.AutoField(primary_key=True) ingrediente = models.TextField() nomes = models.ForeignKey('Nomes', models.DO_NOTHING, blank=True, null=True) class Meta: managed = False db_table = 'ingredientes' class Nomes(models.Model): id = models.AutoField(primary_key=True) # AutoField? nome = models.TextField() class Meta: managed = False db_table = 'nomes' views.py from django.shortcuts import render from .models import Ingredientes, Nomes, Fotos def post_list(request): termo_busca = request.GET.get('pesquisa') if termo_busca: a = Ingredientes.objects.all().filter(ingrediente__contains=termo_busca) # a = a.exclude(ingrediente__icontains=termo_busca!=termo_busca) busca = [p.nomes_id for p in a] lista = [] for i in busca: nome = Nomes.objects.get(id=i) ingredientes = Ingredientes.objects.filter(nomes_id__in=[i]) foto = Fotos.objects.get(id=i) lista.append([nome, ingredientes, foto]) else: a = Nomes.objects.all()[:10] cont = len(a) lista = [] for i in range(1, cont): nome = Nomes.objects.get(id=i) ingredientes = Ingredientes.objects.filter(nomes_id__in=[i]) foto = Fotos.objects.get(id=i) lista.append([nome, ingredientes, foto]) β¦ -
Django: cannot update css changes
After running my server, my page doesn't show the updates that I've made in the CSS file. My navbar won't recognize a css rule: .navbar-bg {background-color: black;} (i've just tested this rule). However, If I paste this same HTML and CSS code in a site like CodePen it works (my navbar gets a black background). https://codepen.io/ogonzales/pen/KbKzQo The same happens if I run the HTML and CSS from a directory in my PC, so I think it has something to do with Django. What could it be? I've tried also this other answer: python manage.py collectstatic --noinput --clear from here without results: Django won't refresh staticfiles base.html: {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content="{% block metadescription %}{% endblock %}"> <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet"> <link rel="stylesheet" href="{% static 'css/custom.css' %}"> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> {# <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css"#} {# integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous">#} <title>Title</title> </head> <body> <div> <div class="container"> {% include 'navbar.html' %} <div class="container-fluid nav-bar-fixed-top my_top_navbar_div"> {% block content %} {% endblock %} </div> </div> {% include 'footer.html' %} <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="{% static 'js/jquery-3.2.1.slim.min.js' %}"></script> <script src="{% static β¦ -
Many-to-many field vs New Model Django
I'm trying to make followers/following functionality and I've thought of two ways. I can't seem to find solution as to which one is the better way. Solution 1 class User(AbstractUser): followers = models.ManyToManyField('self', symmetrical=False) Solution 2 class Follow(models.Model): following = models.ForeignKey(User, related_name="who_follows") follower = models.ForeignKey(User, related_name="who_is_followed") follow_time = models.DateTimeField(auto_now=True) Thanks -
Error with Mysql datetime in django extract return None
Image captured when i try with django manage.py shell I try to extract month,day from Datetime field django model. But it return None. Help me. I have no idea. -
Created new project in django using virtualenv and its running fine but when I trying to create new app using 'startapp' and again running project
Created new project in django using virtualenv and its running fine but when I trying to create new app using 'startapp' and again running project by command : python3.6 advertisement/manage.py runserver localhost:8000 then throw error : Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f57db4171e0> Traceback (most recent call last): File "/home/ravinder/advertisement/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/ravinder/advertisement/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 112, in inner_run autoreload.raise_last_exception() File "/home/ravinder/advertisement/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/home/ravinder/advertisement/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "/home/ravinder/advertisement/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/ravinder/advertisement/venv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ravinder/advertisement/venv/lib/python3.6/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/home/ravinder/advertisement/venv/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'core' Note : I already added app in setting.py installed app. Please help me to reoslve this issue. -
Why is my Django Unittest failing to load with "ImportError: Failed to import test module: tests"
I cannot figure out what I am doing wrong. I added this simple unit test: from django.test import TestCase from blog.myapp.models import * class AllTests(TestCase): def FooBarTest(self): foo1 = Foo.objects.create(name='foo1') bar1 = Bar.objects.create(name='bar1') FooBar.objects.create(foo=foo1,bar=bar1) foo_from_db = Foo.objects.filter(bar__id=bar1) self.assertEqual(foo1.id,foo_from_db.id) Here is my project layout: . βββ blog β βββ __init__.py β βββ __pycache__ β βββ settings.py β βββ urls.py β βββ wsgi.py βββ db.sqlite3 βββ manage.py βββ myapp β βββ __init__.py β βββ __pycache__ β βββ admin.py β βββ apps.py β βββ migrations β β βββ __init__.py β β βββ __pycache__ β β βββ 0001_initial.py β βββ models.py β βββ serializers.py β βββ templates β β βββ myapp β β β βββ index.html β β β βββ post_detail.html β β βββ post_list.html β βββ tests.py β βββ urls.py β βββ views.py I am using PyCharm and here is how I have the test configured: Now when I run my test I get this output: Testing started at 6:21 PM ... C:\Users\plankton\PycharmProjects\blog\venv\Scripts\python.exe "C:\Program Files\JetBrains\PyCharm Community Edition 2018.2\helpers\pycharm\_jb_unittest_runner.py" --target tests.AllTests Launching unittests with arguments python -m unittest tests.AllTests in C:\Users\plankton\PycharmProjects\blog\blog\myapp Error Traceback (most recent call last): File "C:\Users\plankton\AppData\Local\Programs\Python\Python37-32\lib\unittest\case.py", line 59, in testPartExecutor yield File "C:\Users\plankton\AppData\Local\Programs\Python\Python37-32\lib\unittest\case.py", line 615, in run testMethod() File "C:\Users\plankton\AppData\Local\Programs\Python\Python37-32\lib\unittest\loader.py", line β¦ -
ManyToManyField relationship retrieving no data
I've one structure like this: 1. Author 2. Book 3. AuthorType 4. AuthorBookType A book can have more than one author, and it can have functions inside the book, Author, Co-Author, Part, Helper, Etc: class Book(models.Model): title=models.CharField(max_length=100) class Author(models.Model): name=models.CharField(max_length=100) books=models.ManyToManyField(Book, through='AuthorBookType') class AuthorType(models.Model): description=models.CharField(max_length=100) class AuthorBookType(models.Model): author=models.ForeignKey(Author, on_delete=models.CASCADE) book=models.ForeignKey(Book, on_delete=models.CASCADE) author_type=models.ForeignKey(AuthorType, on_delete=models.CASCADE) My database should looks like this: AUTHOR: __________________________ | ID | NAME | |========================| | 1 | Jhon Doe. | | 2 | Charles Albert | | 3 | Matt Greg | | 4 | Anne Engel | -------------------------- BOOK: __________________________ | ID | NAME | |========================| | 1 | Paradise City | | 2 | Profaned Apple | -------------------------- AUTHOR_TYPE: __________________________ | ID | DESCRIPTION | |========================| | 1 | Author | | 2 | Co-Author | -------------------------- AUTHOR_BOOK_TYPE: _____________________________________________ | ID | AUTHOR_ID | BOOK_ID | AUTHOR_TYPE_ID | |===========================================| | 1 | 1 | 1 | 1 | | 2 | 2 | 1 | 2 | | 3 | 3 | 1 | 2 | | 4 | 3 | 2 | 1 | | 5 | 4 | 2 | 2 | --------------------------------------------- On my views.py i did: class AuthorsListView(ListView) model = Author β¦ -
Load a field in html template with data from a selected ChoiceField
I'm getting stuck in the next situation about loading in real-time a field in the template of Sale Model. I have two models (Item and Sale) related by a ForeignKey. Sale Model class Sale(models.Model): sale_item = models.ForeignKey(Item, on_delete=models.CASCADE) new_price = models.IntegerField() def saveSale(self): self.save() def __str__(self): return self.sale_item.name Item Model class Item(models.Model): name = models.CharField(max_length=40) desc = models.CharField(max_length=150) price = models.IntegerField(max_length=7) pic = models.ImageField(upload_to='items_store') element_choice = ( ('USB', 'USB'), ('PC', 'PC'), ('TEXT', 'Book'), ) element = models.CharField(choices=element_choice, max_length=10) stock = models.IntegerField() is_sale = models.BooleanField(default=False) def saveItem(self): self.save() def __str__(self): return self.name I created a form for the Sale Model class formSale(forms.ModelForm): sale_item = forms.ModelChoiceField(queryset=Item.objects.all(), label='sale_item') new_price = models.IntegerField(label='new_price') class Meta: model = Sale fields = ('sale_item','new_price') In my view, I can save the data of Sale form (loaded in template) just fine but I was in need of a real-time update of a new field called "Current Price" added in the template (it is not saved in the Model, is just to see the data) . It'll get loaded with the price inside the Item selected in the ChoiceField. Ex: I select "USB Reader" from the ChoiceField and the Current Field in the template will load with the price of β¦ -
callback on delete from database?
My Django app uses Amazon S3 storage for the user's data files that they have uploaded. I store a pointer (using the uuid) to the file in the model: model.py: class Gedcom(models.Model): """Gedcom model.""" user = models.ForeignKey(User, on_delete=models.CASCADE) filename = models.CharField(max_length=100, default="") title = models.CharField(max_length=100, default="") uuid = models.CharField(max_length=36, default="") Is there a way to perform a callback of sorts when a gedcom item is deleted (say through either the admin interface or via my other code) that a method is called so that I can delete that file from S3? I could run a management function as part of a cron job that delete unlinked file on S3 if they no longer exist in the local database, but I'm wondering if there is another way to do this that is cleaner? -
Path does not redirect to the right page - Reverse for 'moviesofcinema' with no arguments not found
I am new to Django and I am building a website in which there are different Cinemas and each Cinema has several movies. I am having an issue regarding the path from a specific cinema to its movies. 1) In http://127.0.0.1:8000/cinemas/allcinemas the user can see all the cinemas in a card format 2) If the user clicks a card, he should be redirected to http://127.0.0.1:8000/cinemas/8/movies/moviesofcinema where he can see all the movies of that specific cinema. If I copy and past the links in the searchbar, they work. However, if I click in a cinema card, it does not redirect me to the page in which there are all the movies of that cinema. Instead I get the error message: Reverse for 'moviesofcinema' with no arguments not found with the highlighted error: <a href="{% url 'moviesofcinema' %}" > The error message is in the detailofcinema.html Such html page contails the cinema cards. In each cinema card I created a link so that if the user clicks it, he should be redirected to see all the movies of that specific cinema: <a href="{% url 'moviesofcinema' %}" > <p>Which are the movies offered by this cinema?</p> </a> My cinema urls.py is: from β¦