Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django How to send data in sqlite3 to html
Models.py class Table_st(models.Model): number = models.CharField(max_length=255) name = models.CharField(max_length=255) stat = models.CharField(max_length=255) def __str__(self): return self.number class Food_sts(models.Model): food_id = models.CharField(max_length=255) foodname = models.CharField(max_length=255) price = models.CharField(max_length=255) inorder = models.IntegerField() def __str__(self): return self.foodname class Order_st(models.Model): table = models.ForeignKey(Table_st, on_delete=models.CASCADE) foodname = models.ForeignKey(Food_sts, on_delete=models.CASCADE) amount = models.IntegerField() def __str__(self): return self.table.number class cashier_st(models.Model): table = models.CharField(max_length=255) price = models.IntegerField() def __str__(self): return self.table view.py def customer_finish(request): table = Table_st.objects.get(number='1') allorder = Order_st.objects.get(table=table) #send order to html number = request.POST["number"] context = { 'number' : number, 'allorder' : allorder, } return render(request, 'customer_end.html', context) Error self.model._meta.object_name web_app.models.Order_st.DoesNotExist: Order_st matching query does not exist. I want send all Order_st table is 1 to html -
Django sorting based on first object of many to many field
Here i wanted to sort the user based on the first object of car field .And For Foreign key i was doing like this and this is what i tried. User.objects.all().order_by('car__name'). But for many to many field how can i do it for the first or last object. class Car(models.Model): name = models.CharField(max_length=40) class User(models.Model): name = models.CharField(max_length=40) car = models.ManyToManyField(Car) -
The file "manage.py" did not come with my GitHub sample code
I'm an old-school developer, learning Django and GitHub for the first time. I'd like to study https://github.com/tomwalker/django_quiz, but when installed in my virtual environment, I can't find the file "manage.py". A YouTube Django tutorial suggested I need to run "py manage.py runserver" to start a web server on my local machine. (I was successful starting a server when following THAT tutorial, but I'm now studying source code from GitHub.) There's clearly a difference in age between the sample project on GitHub and my YT tutorial... Can someone please tell me if I'm going about the learning of Django correctly, and if I truly need manage.py to start a server? Thank you! -
Can PyInstaller (or other tools) create an executable file from Django project for production environment?
I want to create an executable file from our Django project. Currently we use Daphne as ASGI server hosting both HTTP and web-socket. I found following link but it seems that PyInstaller is only for Django dev env, not for production. https://github.com/pyinstaller/pyinstaller/wiki/Recipe-Executable-From-Django Am I correct? Is there any other tool allow me to create standalone file for production environment. Many thanks! -
Jenkins pip install failure Python.h: No such file or directory
I am trying to add my django project to Jenkins, but the build fails with following error : _mysql.c:37:20: fatal error: Python.h: No such file or directory compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 Build step contains: #!/bin/bash sudo apt-get install build-essential libssl-dev libffi-dev python3-dev virtualenv -p /usr/bin/python3.6 protogenvenv source protogenvenv/bin/activate pip install -U wheel pip install -r requiremenst.txt python manage.py jenkins --enable-coverage -
OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)")
I am using google app engine My settings file import pymysql # noqa: 402 pymysql.install_as_MySQLdb() if os.getenv('GAE_APPLICATION', None): # Running on production App Engine, so connect to Google Cloud SQL using # the unix socket at /cloudsql/<your-cloudsql-connection string> DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': '/cloudsql/connectionstring', 'USER': 'myusername', 'PASSWORD': 'mypasswor', 'NAME': 'mydbname', } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': '127.0.0.1', 'PORT': '3306', 'USER': 'username', 'PASSWORD': 'mypassword', 'NAME': 'dbname', } } Is is working fine.. Now I try to implement google authentication so used social-auth-app-django after redirecting from google it shows the following error: OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)") connect (/env/lib/python3.7/site-packages/pymysql/connections.py:629) -
Django - If I get an error while saving a model instance, how do I check which field caused the error?
Let's say I have the following model. This is just an example. The real life version has hundreds of fields. class MyModel(models.Model): date1 = models.DateField() date2 = models.DateField() date3 = models.DateField() When I am saving the model, I get the following error - ValidationError: ["'' value has an invalid date format. It must be in YYYY-MM-DD format."] Basically, one of the datefields received an empty string as opposed to a proper date format. However, I don't know whether date1, date2, or date3 is causing the problem. Is there some easy way to check which field returned this ValidationError? -
Django force_login not logging the Django Client in?
I must be missing something obvious here but I can't see it so maybe you can help ? I'm using Pytest to test a Django form and it's creation of an object. I'm using Django Client object and trying to force_login which according to the result is not working since in the response url contains a redirect to the login page as if the user would not be logged in... Why is this happening, what am I doing wrong and how to fix it? Here's the code: from django.test import TestCase, RequestFactory, Client class TestViews(TestCase): @classmethod def setUpClass(cls): super(TestViews, cls).setUpClass() cls.user = mixer.blend(get_user_model()) cls.patient = mixer.blend('patient.Patient', created_by=cls.user) cls.factory = RequestFactory() @pytest.mark.django_db def test_patient_creation_form_valid(self): c = Client() c.force_login(self.user) response = c.post(reverse('NewPatientForm'), { 'name': 'John', 'surname': 'Smith', 'phone': '601123456', 'email': 'john.smith@gmail.com', }) self.assertEqual(response.status_code, 302) np = c.get(response.url) Thanks! -
How can I change data display in Text Input of ModelChoiceField?
Is there any what to change data display in readonly InputField of ModelChoiceField, but retain the primary key of the object for submitting the form? views.py class BookingCreateView(LoginRequiredMixin, CreateView): login_url = 'login' form_class = BookingForm template_name = 'booking_add.html' success_url = reverse_lazy('booking_list') def get_initial(self): initial = super(BookingCreateView, self).get_initial() initial['date'] = datetime.datetime.strptime(self.request.GET.get('date'), '%d-%m-%Y') initial['room'] = get_object_or_404(Room, id=self.request.GET.get('room')) initial['start'] = get_object_or_404(Period, number=self.request.GET.get('start')) return initial def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) forms.py class BookingForm(forms.ModelForm): class Meta: model = Booking fields= ['room', 'date', 'start', 'end'] def __init__(self, *args, **kwargs): initial_args = kwargs.get('initial', None) if initial_args: super(BookingForm, self).__init__(*args, **kwargs) self.fields['room'].widget = forms.TextInput() self.fields['start'].widget = forms.TextInput() self.fields['room'].widget.attrs['readonly'] = True self.fields['date'].widget.attrs['readonly'] = True self.fields['start'].widget.attrs['readonly'] = True self.fields['end'].queryset = Period.objects.get_available_periods( initial_args['room'], initial_args['date'], initial_args['start']) def clean(self): cleaned_data = super(BookingForm, self).clean() now = timezone.localtime(timezone.now()) bookings = Booking.objects.filter(room=cleaned_data['room'], date=cleaned_data['date']) booking_start_time = datetime.datetime.combine(cleaned_data['date'], cleaned_data['start'].start, timezone.get_current_timezone()) booking_end_time = datetime.datetime.combine(cleaned_data['date'], cleaned_data['end'].end, timezone.get_current_timezone()) for booking in bookings: if booking.check_overlap(booking_start_time, booking_end_time): raise forms.ValidationError if now > datetime.datetime.combine(cleaned_data['date'], cleaned_data['start'].end, timezone.get_current_timezone()): raise forms.ValidationError return cleaned_data booking_add.html {% block content %} <main> <div class="reg-form"> <form class="form" method="post" action=""> {% csrf_token %} <label for="room">Phòng</label> {{ form.room }} <label for="date">Ngày</label> {{ form.date }} <label for="start">Ca bắt đầu</label> {{ form.start }} <label for="end">Ca kết thúc</label> {{ form.end }} <button type="submit">Đăng ký</button> … -
Django: get data from array of objects sent by ajax formdata
I would like to access option_rows data that is sent from the front end of the web application. I use an array to store a collection of objects, include text and image, and append it into formdata, send via ajax. The console log of option_rows is as the image below. However, I couldn't access each data in the array. How could I access each element of option_rows? Please also point out what is wrong with the code below as well. Thank for answering. Javascript code: var option_rows = []; option_rows.push([{option_name : option_name, answer : answer, option_img : option_img}]); var formData = new FormData(); formData.append('option_rows', option_rows); $.ajax({ url: "{% url 'add_question' %}", type: 'POST', data: formData, contentType: false, processData: false, cache: false, success: function(){ $("#addModal").html(""); }, }) option_rows log: views.py: def add_question(request): if request.method == 'POST': option_rows = request.POST.get('option_rows') print option_rows print type(option_rows) output: -
How to embed interactive Bokeh or Dash app *with authentication* in Django or Flask?
I know similar questions have been asked here or elsewhere, but I feel like I have read it all and still am unclear on how to solve my specific problem - authentication. I have written a Bokeh app that is interactive, so requires Bokeh server to be run to serve JavaScript. The app is fed by user data from Strava. I would like to make the app available to other people, so I need to include authentication to Strava account. For this reason I thought of incorporating the app in a Django project. From what I have read, there is no "official" way of doing this and my best bet might be spinning the Bokeh app and the Django on their own servers and view the Bokeh app in an iframe HTML element in Django template. But would it be then possible to make the apps somehow talk to each other, so that the authentication I need is made through Django and passed to Bokeh app? Also, would it be possible in such setup for the Bokeh app data to be fed from Django models? I am also willing to switch to other frameworks like Flask and Dash if it … -
Flask Appbuilder Run Error: "IndexError: list index out of range"
My views.py and models.py are as below: views.py: import calendar from flask_appbuilder import ModelView from flask_appbuilder.models.sqla.interface import SQLAInterface from flask_appbuilder.charts.views import GroupByChartView from flask_appbuilder.models.group import aggregate_count from flask_appbuilder.widgets import FormHorizontalWidget, FormInlineWidget, FormVerticalWidget from flask_babel import lazy_gettext as _ from app import db, appbuilder from .models import DB, Table class tableModelView(ModelView): datamodel = SQLAInterface(Table) list_columns = ['table_group.table_db_name', 'table_name', 'ddl'] base_order = ['table_group.table_db_name', 'asc'] show_fieldsets = [ ('Summary', {'fields' : list_columns}) ] add_fieldsets = [ ('Summary', {'fields' : list_columns}) ] edit_fieldsets = [ ('Summary', {'fields' : list_columns}) ] class GroupModelView(ModelView): datamodel = SQLAInterface(DB) related_views = [tableModelView] db.create_all() appbuilder.add_view(GroupModelView, "List DBs", icon="fa-folder-open-o", category="DB", category_icon='fa-envelope') appbuilder.add_separator("Table") appbuilder.add_view(tableModelView, "List Tables", icon="fa-folder-open-o", category="Table", category_icon='fa-envelope') models.py: import datetime from sqlalchemy import Column, Integer, String, ForeignKey, Date from sqlalchemy.orm import relationship from flask_appbuilder import Model mindate = datetime.date(datetime.MINYEAR, 1, 1) class DB(Model): db_name = Column(String(50), unique=True, primary_key=True, nullable=False) def __repr__(self): return self.name class Table(Model): table_name = Column(String(100), primary_key=True) ddl = Column(String(16384), unique=True) table_db_name = Column(Integer, ForeignKey(DB.db_name), nullable=False) table_group = relationship("DB") def __repr__(self): return self.name However, when I run it, it has this error: Traceback (most recent call last): File "run.py", line 1, in <module> from app import app File "/Users/x0m00jk/Platform-Manager/app/__init__.py", line 28, in <module> from app import models, … -
how do i submit csv file from form and export its data to my database in Django
I am trying to make a web app for contact list which shows all the contact in the database on home page . i want to implement a functionality of uploading contacts through home page using csv upload what are the steps to implement this functionality please help me this is my first question on stackoverflow. -
Missing Python package from requirements in Docker image built on Circle 2.0
I use CircleCI for continuous integration to build, test, and deploy a Django application, using Docker, ECR on AWS, and Kubernetes. Recently, I updated my CircleCI config file from 1.0 -> 2.0 to comply with required changes. To ensure everything was working properly, I built and deployed the application using the new configuration file and was successful. A couple days ago, I needed to add a new Python package (Shapely) for a new feature to my application, so I added Shapely==1.6.4.post2 to my requirements file - very simple. I can still build, test, and deploy the application from Circle just fine, and everything appears to be working perfectly, however, when the container is running on my servers the Django process will not start because of an import error (can't find module Shapely, basically it isn't getting installed in the image for some reason?!). I can pull the image from ECR and launch a container and confirm that the package does not get installed, however, checking my build logs in Circle confirms that first it got installed and in subsequent builds pulls from the cache, so I am perplexed as to how it isn't included in the image. Interestingly, the container … -
Custom comment for using django_comments_xtd
Hey I am using the django_comments_xtd as a comment app but encounter some problems. In my settings i have arranged the order in this way in order to override the default form used by django_comments , like this: 'comments', 'django_comments_xtd', 'django_comments', My Custom Model: from django.db import models from mptt.models import MPTTModel, TreeForeignKey from django_comments.models import Comment from django_comments_xtd.models import XtdComment # Create your models here. class MyComment(XtdComment): title = models.CharField(max_length=256) My Custom Form: from django import forms from django.utils.translation import ugettext_lazy as _ from django_comments_xtd.forms import XtdCommentForm from django_comments_xtd.models import TmpXtdComment class MyCommentForm(XtdCommentForm): title = forms.CharField( max_length=256, widget=forms.TextInput(attrs={'placeholder': _('title')}) ) def get_comment_create_data(self): data = super(MyCommentForm, self).get_comment_create_data() data.update({'title': self.cleaned_data['title']}) return data My form for the comment looks like that : <!DOCTYPE html> {% load i18n %} {% load comments %} <form method="POST" action="{% comment_form_target %}" class="form-horizontal"> {% csrf_token %} <fieldset> <input type="hidden" name="next" value="{% url 'comments-xtd-sent' %}"/> <div class="alert alert-danger hidden" data-comment-element="errors"> </div> {% for field in form %} {% if field.is_hidden %}<div>{{ field }}</div>{% endif %} {% endfor %} <div style="display:none">{{ form.honeypot }}</div> <div class="form-group {% if 'comment' in form.errors %}has-error{% endif %}"> <div class="col-lg-offset-1 col-md-offset-1 col-lg-10 col-md-10"> {{ form.comment }} </div> </div> {% if not request.user.is_authenticated or not … -
django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (ORA-02000: missing ALWAYS keyword)
I am new to django, and will appreciate if anyone can help me in its configuration. I want to use my oracle db in settings.py file. I made some changes into it by looking into tnsnames.ora. Below are my changes : tnsnames.ora XE = (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = Kathayat)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = XE) ) ) EXTPROC_CONNECTION_DATA = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1)) ) (CONNECT_DATA = (SID = PLSExtProc) (PRESENTATION = RO) ) ) ORACLR_CONNECTION_DATA = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1)) ) (CONNECT_DATA = (SID = CLRExtProc) (PRESENTATION = RO) ) ) settings.py DATABASES = { 'default':{ 'ENGINE': 'django.db.backends.oracle', 'NAME' : 'XE', 'USER' : 'SYSTEM', 'PASSWORD' : 'password', 'HOST' : 'Kathayat', 'PORT' : 1521, } } After running python manage.py migrate i am getting the error : django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (ORA-02000: missing ALWAYS keyword) -
Django view retrieve model id of instance just created
I have a simple scenario trying to retrieve the id/pk of a model instance created in a view. The model instance is creating fine however the id/pk is returning "None". I thought I was following the code as laid out in the latest documentation but I must be doing something wrong. Models.py class Userdownloads(models.Model): id = models.IntegerField(primary_key=True) created_by = models.ForeignKey(User,on_delete=models.DO_NOTHING, related_name='Download_created_by',null=True,blank=True) created_date = models.DateTimeField(auto_now_add=True) Views.py d = Userdownloads(created_by=request.user) d.save() print(d.id) Ive tried both d.id and d.pk Can anybody help my see where I am going wrong? Any help is much appreciated! -
Django and C++ communication
I need to send some data from my C++ program in my client machine to a Django server in order to process the data with Python and send it back to another client machine. That would be easy if it was something like ajax with javascript using json, but the thing is, I researched a lot and found a library for C++ called Wt, it seems to have what I need, but I have no clue of how I would be able to send the data to a Django view. I couldn't find any useful code specific to this problem, I would appreciate if someone could give me a light of how to do so. -
In Django serializer, how do I serialize both sides of a foreign key relationship?
In my Django code, I have this model: class Swipe(models.Model): user = models.ForeignKey( Profile, related_name='swipes', on_delete=models.CASCADE, null=False, default=None ) SWIPE_CHOICES = ( (1, "left"), (2, "right"), (3, "up"), (4, "down") ) direction = models.IntegerField( choices = SWIPE_CHOICES ) where Profile is my user class. I have a view to display all profiles: class ProfileList(generics.ListCreateAPIView): serializer_class = ProfileSerializer queryset = Profile.objects.all() def perform_create(self, serializer): serializer.save() where ProfileSerializer looks like: class ProfileSerializer(serializers.HyperlinkedModelSerializer): # serializations of other fields class Meta: model = Profile fields = ( 'url', 'id', 'username', 'password', 'first_name', 'last_name', 'email', 'swipes', ) This serialization of my Profile class returns just a URL for 'swipes' (e.g. "[host]/swipe/1"). I know this kind of the opposite of how a foreign key relationship is supposed to work, but is there a way for me to serialize this swipe information to display, for example, the direction of the swipe instead of just a URL to the swipe itself? When serializing a Swipe, I can get the serialization of an associated profile to work by adding "user = ProfileSerializer()". However, when I try to add "swipes = SwipeSerializer()" to my code, the swipes field goes from displaying a list of the URLs to an empty map … -
here are duplicate field(s) in fieldsets
This class raises a systems check django error. The specific error it raises is as pasted below. I have looked through previous posts that suggest it was an error that resulted from migrating to django 2.1 and adding a comma at the end of the fields tuple fixed it. This does not work for me. Any help would be greatly appreciated. SystemCheckError: System check identified some issues: ERRORS: <class 'app.admin.user.UserAdmin'>: (admin.E012) There are duplicate field(s) in 'fieldsets[1][1]'. <class 'app.admin.user.UserAdmin'>: (admin.E012) There are duplicate field(s) in 'fieldsets[2][1]'. <class 'app.admin.user.UserAdmin'>: (admin.E012) There are duplicate field(s) in 'fieldsets[3][1]'. @register(User) class UserAdmin(ModelAdmin): fieldsets = ( (None, {'fields': ('email', 'password',)}), ('Personal info', { 'fields': ('first_name', 'last_name', 'email',)}), ('Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions',)}), ('Important dates', {'fields': ('last_login', 'date_joined',)}) ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'password1', 'password2',), }), ) list_display = ('email', 'first_name', 'last_name', 'username', 'is_staff') list_filter = ('is_staff', 'is_superuser', 'is_active', 'groups',) search_fields = ('email', 'first_name', 'last_name',) ordering = ('email',) filter_horizontal = ('groups', 'user_permissions',) -
Django Rest Framework - How to call method model
I need to call a method from a template. I have the following codes: models.py class Operation(Base): ... hash_code = models.UUIDField(default=uuid4) ... def open_operation(self, user): ... pass views.py class OperationOpenView(APIView): """ patch: """ filter_backends = (filters.DjangoFilterBackend,) filter_class = OperationOpenFilter def patch(self, request, id): user = request.user operation = Operation.objects.get(pk=id) serializer = OperationOpenSerializer(operation, data=request.data, partial=True) if serializer.is_valid(): serializer.save() serializer.instance.open_operation(user) return Response(data={'operation': operation, 'user': user}, status=status.HTTP_200_OK) else: return Response(code=400, status=status.HTTP_400_BAD_REQUEST) serializers.py class OperationOpenSerializer(serializers.ModelSerializer): class Meta: model = Operation fields = ('id', ) depth = 1 filters.py class OperationOpenFilter(filters.FilterSet): id = filters.NumberFilter( label='id', required=True, help_text='ID' ) class Meta: model = Operation fields = ['id',] urls.py path(r'operations/open', views.OperationOpenView.as_view()), tests.py @pytest.mark.django_db def test_view(client_api_logged): response = client_api_logged.patch('/api/operations/open', kwargs= {'id': '1'}) assert response.status_code == 200 I'm not getting it to work, getting the error: "TypeError at /api/operations/open patch() missing 1 required positional argument: 'id'" any light at the end of the tunnel? thank you all -
no such column: chat_conversation.created_date
Local webapp error I am trying to view a Conversation model I created in Python 3.7 with Django. I am new to Python, Django, and making webapps. I have done the makemigrations and migrate commands, but I still get the "no such column: chat_conversation.created_date" error. Here is the model.py from django.db import models from django.utils import timezone import uuid class Conversation(models.Model):#keeps track of conversation id id = models.UUIDField(primary_key=True, default=uuid.uuid4) created_date = models.DateTimeField(default=timezone.now) This is what I have for the views.py from django.shortcuts import redirect from django.shortcuts import render from django.http import HttpResponse from django.utils import timezone from .models import Conversation from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect def con_list(request): con = Conversation.objects.filter(created_date__lte=timezone.now()).order_by('created_date') return render(request, 'chat/con_list.html', {'con': con}) def con_new(request, pk): if request.method == "CONVERSATION": #form = ConversationForm(request.CONVERSATION) if form.is_valid(): #conversation = form.save(commit=False) conversation.created_date = timezone.now() conversation.save() return redirect('con_list') #else: #form = ConversationForm() return render(request, 'chat/post_list.html' )#{'form': form}) def con_edit(request, pk): conversation = get_object_or_404(Conversation, pk=pk) if request.method == "CONVERSATION": #form = ConversationForm(request.CONVERSATION, instance=conversation) if form.is_valid(): #conversation = form.save(commit=False) conversation.created_date = timezone.now() conversation.save() return redirect('con_list') #else: #form = ConversationForm(instance=conversation) return render(request, 'chat/con_edit.html' )#{'form': form}) I have commented some parts out that I would like to add back, but after i … -
'invalid_choice' in field foreing key django
I have a problem with a foreing key field that I initialize with a queryset, the form is displayed but at the time of sending data the error 'in to_python raise ValidationError (self.error_messages [' invalid_choice '], code =' invalid_choice ')' appears' . I know there is a way to invalidate the 'to_python' method but I still can not get it to work. I would appreciate any help. My view: class PlanesCreate(generic.CreateView): model= Plan_Estudios template_name= 'ControlEscolar/Administracion/planes/planes_form.html' form_class= PlanForm success_url = reverse_lazy('ControlEscolar:planes_filtro') def get_form_kwargs(self): kwargs = super(PlanesCreate, self).get_form_kwargs() kwargs.update({'programa': self.request.session['programa']}) return kwargs My form: class PlanForm(forms.ModelForm): class Meta: model = Plan_Estudios fields = "__all__" widgets = { 'nombreplan': forms.TextInput(attrs={'class':'form-control'}), 'programa': forms.Select(attrs={'class':'form-control'}), } def __init__(self, *args, **kwargs): p=kwargs.pop('programa', None) super(PlanForm, self).__init__(*args, **kwargs) query=Programa_Academico.objects.filter(pk=p) self.fields['programa'].queryset=query #Inicialize field with query My model: class Plan_Estudios(models.Model): nombreplan= models.CharField(max_length=30) programa= models.ForeignKey(Programa_Academico, on_delete=models.SET_NULL, null=True) def __str__(self): return self.nombreplan class Programa_Academico(models.Model): nombreP= models.CharField(max_length=50) siglas= models.CharField(max_length=10) def __str__(self): return self.siglas Error: to_python raise ValidationError(self.error_messages['invalid_choice'], code='invalid_choice') KeyError: 'invalid_choice' -
Can't override Django's email subject line
I have a registration folder in my Django app, and I'm using django.contrib.auth.views for all the user log in and registration things. Anyway, I set up my password_reset_form.html and everything works well, except I can't seem to set the email subject line. Every resource I'm finding online says I can just add password_reset_subject.txt to my registration folder (on the same level as all my user html templates), and that should override the django default. However, that's not working. I would be willing to switch to the send_mail() approach but I like how the built in django.auth one sends a tokened link to change_password. Is there any reason my password_reset_subject.txt would be ignored? Thanks in advance. -
Django - FileField vs ImageField
I am a django beninner. can I have a field can upload file and image both? Field field can upload file only while imageField can only upload image?