Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Display a value from a foreign key model in a combo box and select it
So I have the following requirement: I need to display a value from a combo box in Django, the Project Description specifically, but I just can't figure out to get the correct way to render it as I see nothing. Here's my configuration: models.py class Project(models.Model): projectID = models.AutoField(primary_key=True, db_column="Id", db_index=True, verbose_name='Project ID') description = models.CharField(max_length=900) def __str__(self): return str(f'{self.projectID}, {self.description}') def get_description(self): return str(self.description) class PM(models.Model): PMid = models.AutoField(primary_key=True, db_column="Id", db_index=True) PMNumber = models.CharField(max_length=50, unique=True, db_column="PMNumber") description = models.CharField(max_length=600) projectId = models.ForeignKey(Project, on_delete=models.CASCADE, db_column="ProjectID", related_name='+') def __str__(self): return str(f'{self.PMid}, {self.PMNumber}, {self.description}') def get_project_description(self): Project.objects.all().values_list('projectID', 'description') These are the forms: forms.py """ PM Forms """ #Django imports from django import forms #Project imports from pm.models import PM class PMForm(forms.ModelForm): """PMForm""" class Meta: model = PM fields = ('PMNumber', 'description', 'projectId') And this is the view: views.py """Pm Views """ #Django imports from django.urls import reverse_lazy from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import CreateView #Forms import from pm.forms import PMForm #Models import class CreatePMView(LoginRequiredMixin, CreateView): template_name = 'pm/new.html' form_class = PMForm success_url = reverse_lazy('project:feed') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['user'] = self.request.user return context def get_description(self): return self.request.project.description Here's the HTML that I'm trying to render to display the Project … -
Why does Django give me a 404 error for only one url pattern?
I'm following thenewboston's Django tutorial and no one seems to be running into this problem. I have created a music app with an index view which works fine. Now I want to create detailed views for music albums. music.urls.py: from django.urls import path from . import views urlpatterns = [ # /music/ path(' ', views.index, name='index'), # /music/21/ path('music/<int:album_id>/', views.detail, name='detail'), ] music.views.py: from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("<h1>This is the music app homepage") def detail(request): return HttpResponse("<h2>Detail " + str(album_id) + "</h2>") I do get a few warnings in Visual Studio Code stating that Django is unable to import some modules. But if that was the cause then url/music should also return a 404 error? -
Read-only file system: '/srv/media/house_preview/question_4.PNG'
I have a simple Django app deployed to App Engine, which connects to Cloud SQL (PostgreSQL) instance. This Django app allows users to login/register and put up items for sale. Login/register works fine, but when putting up items for sale I get the following error: Request Method: POST Django Version: 3.0.3 Python Version: 3.7.7 Installed Applications: ['projects', 'blog', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/env/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/srv/projects/views.py", line 28, in createListing link.save() File "/srv/projects/models.py", line 24, in save super(Listing_Database, self).save(*args, **kwargs) File "/env/lib/python3.7/site-packages/django/db/models/base.py", line 746, in save force_update=force_update, update_fields=update_fields) File "/env/lib/python3.7/site-packages/django/db/models/base.py", line 784, in save_base force_update, using, update_fields, File "/env/lib/python3.7/site-packages/django/db/models/base.py", line 887, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "/env/lib/python3.7/site-packages/django/db/models/base.py", line 926, in _do_insert using=using, raw=raw, File "/env/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/env/lib/python3.7/site-packages/django/db/models/query.py", line 1204, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "/env/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1383, in execute_sql for sql, … -
How to return PDF file in an Graphql mutation?
I'm using React and Graphql on the frontend and Django and Graphene on the backend. I want to be able to download a pdf file of a report. I try to do it using mutation as follows: const [createPdf, {loading: createPdfLoading, error: createPdfError}] = useMutation(CREATE_PDF) const handleCreatePDF = async (reportId) => { const res = await createPdf({variables: {reportId: parseInt(reportId) }}) debugger; }; export const CREATE_PDF = gql` mutation ($reportId: Int!) { createPdf (reportId: $reportId){ reportId } } `; On the backend I have something like this: class CreatePDFFromReport(graphene.Mutation): report_id = graphene.Int() class Arguments: report_id = graphene.Int(required=True) def mutate(self, info, report_id): user = info.context.user if user.is_anonymous: raise GraphQLError("You are not logged in!") report = Report.objects.get(id=report_id) if not report: raise GraphQLError("Report not found!") if user != report.posted_by: raise GraphQLError("You are not permitted to do that!") html_string = render_to_string('report.html', {'report_id': 1}) pdf_file = HTML(string=html_string) response = HttpResponse(pdf_file, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="rapport_{}"'.format(report_id) return response # return CreatePDFFromReport(report_id=report_id) When I uncomment return CreatePDFFromReport(report_id=report_id) it works fine. But I want to return pdf file. Is there any possibility to do that? Thanks. -
Django/ Django_plotly_Dash (Exception Value: expected string or bytes-like object)
When I try to render a plot by Django_Plotly_Dash, I get a TypeError. Please, see below my code snippets and a taceback that I get. I've been trying to understand where the problem appears for hours but nothing comes into my mind. Could anybody, please, help me you here? simpleexample.py import dash_core_components as dcc import dash_html_components as html from django_plotly_dash import DjangoDash external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = DjangoDash('SimpleExample', external_stylesheets=external_stylesheets) app.layout = html.Div([ html.H1('Square Root Slider Graph'), dcc.Graph(id='slider-graph', animate=True, style={"backgroundColor": "#1a2d46", 'color': '#ffffff'}), dcc.Slider( id='slider-updatemode', marks={i: '{}'.format(i) for i in range(20)}, max=20, value=2, step=1, updatemode='drag', ), ]) welcome.html {% extends 'base.html' %} {% load static %} {% block content %} {% load plotly_dash %} <block> <div> {% plotly_app name='SimpleExample' ratio=0.45 %} </div> </block> {% endblock %} views.py from django.urls import path from . import views from home.dash_apps.finished_apps import simpleexample urlpatterns = [ path('', views.home, name='home') This is the traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.0 Python Version: 3.7.7 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home.apps.HomeConfig', 'django_plotly_dash.apps.DjangoPlotlyDashConfig', 'channels', 'channels_redis'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template C:\Users\milos\statisticsofcorona\templates\base.html, error at line 0 expected string or bytes-like object 1 : {% load … -
Why django class based View (DetailView) only works with a specific variable names
my English is not good, I apologize in advance. My following question is to understand why the variable template_name for example, with class by DetailView only works with exactly that variable name. For example in views.py: from django.views.generic import DetailView # /appPruebaDos/detailView/<int:pk> class DetailViewObject(DetailView): model = Articulo template_name = "plantillaDetailView.html" # varible fijado del tipo DetailView Why I can't use other variable like(this don't work): # /appPruebaDos/detailView/<int:pk> class DetailViewObject(DetailView): model = Articulo templateName = "plantillaDetailView.html" # varible fijado del tipo DetailView I think template_name field is defined in the DetailView dependencies, but how and where is defined? -
How do I get all current sessions from django?
I recently struggled to do this so i thought I would answer my own question to help. Found this out after playing with dir(Session.objects), after importing from django.contrib.sessions.models import Session. -
Hourly automatic update of Django database while avoiding duplicate entries
I know this question has been asked in the past, but it seems a lot has changed in the past few years so I'm hoping to find an up-to-date answer. I have a django app that collects third party data which is updated hourly (roughly) and saves that data to the appropriate models in my mySQL database. Right now I just run the database update view each time I manually reload my homepage. Is there a way to have this process automated so that data collection and database update is carried out every hour on its own? I've seen multiple options including celery or django managers (?) and I'm wondering what the current most popular method is. Secondary question. Sometimes the third party data provider updates their data irregularly (i.e., they miss an hour). This could potentially lead to my script collecting the same set of data more than once. Is there a way I can prevent it from saving that duplicate to my database? My initial thought is to scrape the data, then query my db to ensure that data does not already exist before saving it. Is this the preferred method or is there a faster option, as … -
How to track model changings in Django?
How to make model history in Django and do it in a safe way? For example, I have Balance and Transaction. How to link these models to reduce manually management? from django.db import models from djmoney.models.fields import MoneyField import django.contrib.auth.models as authm # Create your models here. class Balance(models.Model): user = models.ForeignKey(authm.User, primary_key=True) balance = MoneyField(max_digits=14, decimal_places=2, default_currency='RUB') class Transaction(models.Model): type = [('I', 'Income'), ('O', 'Outcome')] balance = models.ForeignKey(Balance) amount = MoneyField(max_digits=14, decimal_places=2, default_currency='RUB') type = models.CharField(max_length=1, choices=type) -
How to store the contact's phone number in memory in ChatBot using python-telegram-bot
I am working with python-telegram-bot building a menu system. I created a Django project, as shown below, using Webhook to connect to Telegram. When the first message is sent, I ask the contact for their phone number and keep this number so I don't need to ask for it in the next messages in the conversation, but it’s not working. I tried to store it in request.session, but apparently every new message is a new session and so I lose the number. How can I solve this? Every help is welcome. view.py import json from django.http.response import HttpResponse from django.views.decorators.csrf import csrf_exempt from core.message import proccess @csrf_exempt def event(request): json_telegram = json.loads(request.body) proccess(request, json_telegram) return HttpResponse() messages.py import telegram from bot_webhook.settings import TOKEN from telegram import InlineKeyboardMarkup, InlineKeyboardButton bot = telegram.Bot(token=TOKEN) def proccess(request, json_telegram): if 'login' in request.session: msg_options(json_telegram) else: try: request.session['login'] = json_telegram['message']['contact']['phone_number'] msg_options(json_telegram) except: msg_login(json_telegram) def msg_login(json_telegram): chat_id = json_telegram['message']['from']['id'] reply_markup = telegram.ReplyKeyboardMarkup( [[telegram.KeyboardButton('Click to Login', request_contact=True)]], resize_keyboard=True, one_time_keyboard=True ) bot.sendMessage(chat_id, 'I need to authorize your access.', reply_markup=reply_markup) def msg_options(json_telegram): chat_id = json_telegram['message']['from']['id'] first_name = json_telegram['message']['from']['first_name'] last_name = json_telegram['message']['from']['last_name'] button_list = [] button_list.append(InlineKeyboardButton('Button One', callback_data='query_one')) button_list.append(InlineKeyboardButton('Button two', callback_data='query_two')) reply_markup = InlineKeyboardMarkup(build_menu(button_list, n_cols=2)) bot.send_message(text='Hello {0} {1}!\nI have this options:'.format(first_name, … -
Django Window annotation using combined with distinct clause
I have a Django model stored in a Postgres DB comprised of values of counts at irregular intervals: WidgetCount - Time - Count I'm trying to use a window function with Lag to give me a previous row's values as an annotation. My problem is when I try to combine it with some distinct date truncation the window function uses the source rows rather than the distinctly grouped ones. For example if I have the following rows: time count 2020-01-20 05:00 15 2020-01-20 06:00 20 2020-01-20 09:00 30 2020-01-21 06:00 35 2020-01-21 07:00 40 2020-01-22 04:00 50 2020-01-22 06:00 54 2020-01-22 09:00 58 And I want to return a queryset showing the first reading per day, I can use: from django.db.models.functions import Trunc WidgetCount.objects.distinct("date").annotate(date=Trunc("time", "day")) Which gives me: date count 01/01/20 15 01/01/21 35 01/01/22 50 I would like to add an annotation which gives me yesterday's value (so I can show the change per day). date count yesterday_count 01/01/20 15 01/01/21 35 15 01/01/22 50 35 If I do: from django.db.models.functions import Trunc, Lag from django.db.models import Window WidgetCount.objects.distinct("date").annotate(date=Trunc("time", "day"), yesterday_count=Window(expression=Lag("count"))) The second row return gives me 30 for yesterday_count - ie, its showing me the previous row before … -
Django get_foo_display method on a queryset multiple result set
I am working on Django Rest Framework backend for React frontend and have a scenario where a model that I'm working with have a number of choice fields setup on Django side. Using the same key values I built fields on React side such as 'm','Male'. The problem I have is I can create a new record and send those key values (e.g. 'm'), but when I call an API to get me all records and display on the webpage, I want to see the full values coming from API directly. I know about the get_foo_display method and I used it on the Serializer and it did work for retrieving the results, but then broke the creation (post) method with below error: Got a TypeError when calling Person.objects.create(). This may be because you have a writable field on the serializer class that is not a valid argument to Person.objects.create(). You may need to make the field read-only, or override the PersonSerializer.create() method to handle this correctly. Is there a simple way to have both scenarios covered: 1. When creating records, send in key values associated with choice values. 2. When getting result sets using GET method, show full value of … -
Django Custom Inclussion Tags
I'm trying to use custom inclusion tag to display the latest 3 post titles on my blog sidebar, I don't seem to get any errors but my results didn't display either. Inclusion tag in[latest_posts.html file]1 templatestag.py including the template in base.html -
Django does not safe the values of the BooleanFields
I have the following form with few boolean fields: class RegistrationForm(UserCreationForm): guardianSource = forms.BooleanField(widget=forms.CheckboxInput(attrs={'id':'guardianSource'}),required=False) bbcSource = forms.BooleanField(required=False) independentSource = forms.BooleanField(required=False) categoryCoronaVirus = forms.BooleanField(required=False) categoryPolitics = forms.BooleanField(required=False) categorySport = forms.BooleanField(required=False) #Telling the registration form what kind of data we are going to be modelling/ what the form needs to look like class Meta: model = Account fields = ("username", "password1", "password2", "guardianSource", "bbcSource", "independentSource", "categoryCoronaVirus", "categoryPolitics", "categorySport") The register template looks as following: <form class="form-signin" method="POST">{% csrf_token %} <h1 class="h3 mb-3 font-weight-normal">Register</h1> <label for="username" class="sr-only">Username</label> <input type="text" name="username" id="username" class="form-control" placeholder="User name" required autofocus> <label for="inputPassword1" class="sr-only">Password</label> <input type="password" name="password1" id="inputPassword1" class="form-control" placeholder="Password" required> <label for="inputPassword2" class="sr-only">Password</label> <input type="password" name="password2" id="inputPassword2" class="form-control" placeholder="Confirm Password" required> <br> <div class="form-control"> <p><b>Please choose news sources!</b></p> <label for="guardianSource" >The Guardian</label> <input type="checkbox" name="source" id="guardianSource"> <br> <label for="bbcSource" >BBC News</label> <input type="checkbox" name="source" id="bbcSource"> <br> <label for="independentSource" >The Independent</label> <input type="checkbox" name="source" id="independentSource"> </div> <br> <div class="form-control"> <p><b>Please choose news category!</b></p> <label for="categoryCoronaVirus" >Corona Virus</label> <input type="checkbox" name="category" id="categoryCoronaVirus"> <br> <label for="categoryPolitics" >Politics</label> <input type="checkbox" name="category" id="categoryPolitics"> <br> <label for="categorySport" >Sport</label> <input type="checkbox" name="category" id="categorySport"> </div> {% for field in registration_form %} <p> {% for error in field.errors %} <p class="alert alert-danger card-header text-center flashit"> {{ … -
Type <class 'authorizenet.apicontractsv1.STD_ANON_15'> cannot be created from: 4007000000027
I'm i litle lost here , i know that the form pass the credit card but we can see in the error authorizenet raise an error. someone help if possible !! thanks! def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): card_number = request.POST.get('card_number') Payment.objects.charge_credit_card(Decimal ('27.55'), card_number, request.POST) return HttpResponseRedirect('/success/') return render(request, self.template_name, {'form': form}) -
TypeError: __init__() got an unexpected keyword argument 'validators'
I want to validate phone_number in my form with RegexValidator I find this validator in here and it works all right in model.py but in forms.py I get this error can any one help me? here is my model.py: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) #additional blood_type = models.CharField(max_length=2,blank=True) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True) description = models.TextField(blank=True) case =models.CharField(max_length=30,blank=True) def __str__(self): return self.user.username and this is forms.py: class UserProfileForm(forms.ModelForm): phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") class Meta(): model = UserProfile fields = ('case', 'blood_type', 'phone_number','description') labels = { 'description': '', 'case':'', 'blood_type':'', 'phone_number':'', } widgets = { 'phone_number': forms.TextInput(attrs={'placeholder':'Phone number'},validators=[phone_regex]), 'blood_type': forms.Select(choices=BLOOD_TYPES), 'case': forms.Select(choices=CASE), 'description': forms.Textarea(attrs={'class':'customtext', 'placeholder':'Please write your ilness...'}), } -
Difference between Wagtail admin Site and Django admin Site?
This may be a basic question, but it puzzles me and I couldn't find an answer on the web. In my Wagtail admin I see a menu entry 'Sites' with (in my case) one item, in which I can configure a host name, a port, a site name, a Wagtail root page and a boolean 'is default site'. When I log in to django-admin (for the same project obviously) I see a menu entry 'Sites' with one item, with only two fields: domain name, display name. Changing it in one admin doesn't seem to change anything in the other. E.g. I needed to change the domain name (default in Django 'example.com') but couldn't find that in Wagtail admin. Are the two related in some way, and if so, why don't I see the same fields on both admins? Am I missing something obvious? -
Django Bootstrap card-deck if forloop divisibleby
I'm trying to use bootstrap cards. But I have problem. When I adding new post to be display as a card, and i display more then 5 they starting to squize. I'm was try to use forloop counter to start new line every time when it display more then 5 cards. But Im doing something wrong. I read everything and everywhere is the same thing. But I'm for sure doing this wrong. <div class="card-deck"> {% for post in post_list %} {% if forloop.counter0|divisibleby:3 %} <div class="card border-primary mb-3" style="max-width: 20rem;"> <a href="{% url 'post_detail' post.slug %}"> <img style="height: 200px; width: 100%; display: block;" src="{{ post.thumb.url }}" alt="Card image"></a> <div class="card-header">Header</div> <div class="card-body"> <h4 class="card-title">{{ post.title }}</h4> <p class="card-text">{{post.content|slice:":200" }}</p> </div> </div> {% endif %} </div> </div> {% endfor %} Reference image -
In Django how to user Application A serializer in Application B and manipulate a value using SerializerMethodField
App a --> serializer.py App b --> serializer.py Now in a App I need to import b serializer.py In app a from b.serializers import aserializers class aserializers(serializers.ModelSerializer): Now I've a filed "is_prod" in a serializers whose value is either 1 or 0 if it is 1 it should prod and if it's 0 it should show non-prod. I can't use App b serializers as it's already written and used in various places. -
how to make a multiple type users in django?
I am Building an app for a Charity and I need to make a system with different forms for six different user types. the six types are : patients(with the ability to work or not), founders & managers, regular users, volunteers, Financial & work sponsors. patients form has : name, the date of injury, injury percentage, age, gender and some other stuff other users have unique fields like patients for themselves. for now I just want to make the forms and add users from the admin page. should I make six individual forms and inherit from user creation form? if so, how to separate them in the admin page? Can I use one authentication for all of them? I am so confused! could you please help me to make a multiple user sign up forms! I have no idea about the code!!! thanks for the responses -
I have a Jupyter notebook / SciKit model for NBA predictions I want to publish online
Honestly not sure how to frame this as effectively as possible. I built an NBA prediction model that outputs results of matches as well as probabilities of victory. Basically, it inputs certain stats about both teams and outputs the likelihood of each team winning. I built this on a local Jupyter Notebook, and I run one notebook to compile today's schedule and stats into a csv, and turn this csv in a panda df and run it through my model. I know the NBA season has been postponed but I wanted to build this website anyways, where basically I wanted to publish my predictions for friends and others to see. There are 2 ways I see this being done but correct me if I'm wrong: 1. Where I run the model locally and update a database with these predictions and my website will pull the data from this database. 2. Ideally, I would like the model to be hosted online and run automatically every day and execute the scripts that I would run locally to compile daily predictions without my input. Basically I am looking for help on what type of infrastructure I should actually use and what I need … -
Django queryset with partial nested lists
I have two models : class Project(models.Model): name = models.CharField(max_length=255) client = models.ForeignKey(client, on_delete=models.CASCADE) class Client(model.Model): name = models.CharFiled(max_length=255) Assume my data is : Client table - [{id:1,name:client1}, {id:2, name:client2} Project table - [{id:1, name: project1, client:1}, {id:2, name: project2, client:1}, {id:3, name: projects, client:2}] a Client.objects.all() QuerySet will return two objects, client1 and client2 which client 1 has 2 projects and client2 have only 1. I am trying to order a QuerySet by a project name, but per Client object. doing so this way : clients = Client.objects.order_by("project__name") as Expected the result will provide 3 clients object, 2 for client1 and one for client 2. However, my problem is that each client object contains all the projects and not only the specific ordered one. I am trying to filter for each client object, even if the client is the same only the requested ordered projects. I can theoretically do that manually after receiving the queryset, but I assume there is a way to do it because the request does know which project specifically cause the creation of a new row in the queryset. -
How to run the packaged application from django's polls tutorial?
https://docs.djangoproject.com/en/3.0/intro/reusable-apps/ After it's packaged, the documentation says that 'With luck, your Django project should now work correctly again. Run the server again to confirm this.'. In this tutorial, to start the server, do this: python manage.py runserver But after this is packaged and installed to the user directory, it has been moved out of the project, and 'manage.py' isn't available. How to run the server and test the newly installed package? This may be a silly question, but the doc does lack a key sentence to tell how to start the server to run the installed package. -
Override Django's ManyToManyField with Custom fields and Access It
I have created ManyToManyPatchedField by overriding class ManyToManyField. In the new class, I have added a new column called created (Datetime Field). I did this by overriding function contribute_to_class and create_many_to_many_intermediary_model to add a new column created. The patched Django function looks like this. def create_many_to_many_intermediary_patched_model(field, klass): """ Override function create_many_to_many_intermediary_model in django.db.models.fields.related to add new columns created and foreign key to Comments table """ from django.db import models def set_managed(model, related, through): through._meta.managed = model._meta.managed or related._meta.managed to_model = resolve_relation(klass, field.remote_field.model) name = '%s_%s' % (klass._meta.object_name, field.name) lazy_related_operation(set_managed, klass, to_model, name) to = make_model_tuple(to_model)[1] from_ = klass._meta.model_name if to == from_: to = 'to_%s' % to from_ = 'from_%s' % from_ meta = type(str('Meta'), (object,), { 'db_table': field._get_m2m_db_table(klass._meta), 'auto_created': klass, 'app_label': klass._meta.app_label, 'db_tablespace': klass._meta.db_tablespace, 'unique_together': (from_, to), 'verbose_name': _('%(from)s-%(to)s relationship') % {'from': from_, 'to': to}, 'verbose_name_plural': _('%(from)s-%(to)s relationships') % {'from': from_, 'to': to}, 'apps': field.model._meta.apps, }) # Construct and return the new class. return type(str(name), (models.Model,), { 'Meta': meta, '__module__': klass.__module__, from_: models.ForeignKey( klass, related_name='%s+' % name, db_tablespace=field.db_tablespace, db_constraint=field.remote_field.db_constraint, on_delete=CASCADE, ), to: models.ForeignKey( to_model, related_name='%s+' % name, db_tablespace=field.db_tablespace, db_constraint=field.remote_field.db_constraint, on_delete=CASCADE, ), # Custom created field 'created': models.DateTimeField(auto_now_add=True) }) When I try to access the row using model1.model2.through.objects.all().values(), it returns … -
django MultiValueDictKeyError and RuntimeError in saving a form's data in database
I am trying it very hard but I didn't find what I am missing. I have made a form that contains fields like the first name, last name, address, city, state, zip and one Image file from the user. But I am getting this error when I was trying to post data by views. MultiValueDictKeyError at /submit_your_task 'image' Request Method: POST Request URL: http://127.0.0.1:8000/submit_your_task Django Version: 2.2.4 Exception Type: MultiValueDictKeyError Exception Value: 'image' and this is my views.py for that form def submit_your_task(request): if request.method == 'POST': first_name = request.POST['first_name'] last_name = request.POST['last_name'] address = request.POST['address'] phone = request.POST['phone'] city = request.POST['city'] state = request.POST['state'] zip = request.POST['zip'] image = request.FILES['image'] fs = FileSystemStorage() file = fs.save(image.name, image) url = fs.url(file) submit_task = SubmitYourTask(first_name=first_name, last_name=last_name, address=address, phone=phone, city=city, state=state, zip=zip, image=url) submit_task.save() return render(request, 'submit_task.html') and this is urls.py from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', views.home, name='home-page'), path('about/', views.about_us, name='about'), path('signup/', views.signup, name='signup'), path('submit_your_task/', views.submit_your_task, name='submit_your_task'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And when I put the slash after 'submit_your_task' it gives me RuntimeError RuntimeError at /submit_your_task You called this URL via POST, but the …