Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add view count for articles?
Currently I am developing a blog that contains articles. I wish to add the view count for the articles so that when a user views the article page, that view count will increase. This is for my models.py file: class Article(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='kbase_posts') # body = models.TextField() #body = RichTextField(blank=True, null=True) body = RichTextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() # The default manager. published = PublishedManager() # Our custom manager. tags = TaggableManager() #topic = models.CharField(max_length=250, blank = True) -
Why am I getting 'Foreign Key Mismatch' when trying to save a model form in Django?
I am trying to save an instance of a modelform in Django. I have setup a template to input information to the form and a view to handle the save. The form validates fine, but when trying to save it generates a foreigkey mismatch error. What am I doing wrong here? I am running Django 2.0.0. I have already tried adding and removing the primary_key option without any luck and deleting my sqlite database, clearing all pycache, and migrating again. The problem persists. #models.py from django.db import models import uuid from users.models import Company, CustomUser from delivery import settings class Location(models.Model): location_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) address = models.CharField(max_length = 120) date_added = models.DateField(auto_now_add = True) class Shipment(models.Model): date_created = models.DateField(auto_now_add=True) sender_company = models.ForeignKey(Company, on_delete = models.PROTECT, related_name='sender') receiver_company = models.ForeignKey(Company, on_delete = models.PROTECT, related_name='receiver') origin = models.ForeignKey(Location, on_delete = models.SET_DEFAULT, default = 'Location no longer active.', related_name='origin') destination = models.ForeignKey(Location, on_delete = models.SET_DEFAULT, default = 'DESTINATION UNKNOWN', related_name='destination') expected_arrival = models.DateField() weight = models.FloatField() current_handler = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.SET_DEFAULT, default = 'UNKNOWN') shipment_id = models.UUIDField(unique=True, primary_key = True, default=uuid.uuid4, editable=False) #forms.py from django import forms from .models import Location, Shipment class LocationRegisterForm(forms.ModelForm): class Meta: model = Location fields … -
Change button depending on like status
I am attempting to add a post liking system to my website. I already have the functionality to like and unlike posts, however I can't get the button value to change in the template. models.py class Post(models.Model): file = models.FileField(upload_to='files/') summary = models.TextField(max_length=600) pub_date = models.DateTimeField(auto_now=True) user = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.ManyToManyField(User, related_name='likes') is_liked = models.BooleanField(default=False) views.py def likepost(request, pk): if request.method == 'POST': user = request.user post = get_object_or_404(Post, pk=pk) if post.likes.filter(id=user.id).exists(): post.is_liked = True post.likes.remove(user) else: post.is_liked = False post.likes.add(user) return redirect('home') home.html {% if post.is_liked == True %} <a href="javascript:{document.getElementById('like__post').submit()}"><button class="btn btn-primary btn-lg btn-block"><span class="oi oi-caret-top"></span> Like {{ post.total_likes }}</button></a> {% else %} <a href="javascript:{document.getElementById('like__post').submit()}"><button class="btn btn-primary btn-lg btn-block"><span class="oi oi-caret-top"></span> Unlike {{ post.total_likes }} </button></a> {% endif %} <form id="like__post" method="POST" action="{% url 'likepost' post.id %}"> {% csrf_token%} <input type="hidden"> </form> -
Replace an image through Django admin panel
I want to be able to replace my homepage image from the Django admin panel. I can upload to my ../media/homepage directory just fine but I want to first delete any image named "bg.jpg" and rename my new image to "bg.jpg". models.py from django.db import models from django.core.files.storage import FileSystemStorage from datetime import datetime class Homepage(models.Model): homepage_image = models.ImageField(upload_to="../media/homepage",blank=True) image_text = models.CharField(max_length=200, blank=True) header_title = models.CharField(max_length=200, blank=True) header_text = models.TextField(blank=True) class Meta: verbose_name_plural = "Homepage" def __str__(self): return "Homepage" -
Django rest framework and XML. Change item_tag_name, root_tag_name and other
I set up a rest framework in my project according to Quickstart Everything works, but, as it usually happens, not without questions! My serializer.py: class kvSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = kv fields = ['title', 'price', 'address'] My views.py: class kvViewSet(viewsets.ModelViewSet): queryset = listings.objects.all() serializer_class = kvSerializer My XML: Object title 100 object address Question: How can I change tags <root> and <list-item>? <root> should be called <feed> <list-item> should be called <offer> Before tag <offer> need to insert tag <creation-date> My final XML should be as follows: <feed> <creation-date>Date</creation-date> <offer id=1> <title> Object title </title> <price>100</price> <address> object address </address> </offer> <offer id=2> <title> Object title </title> <price>100</price> <address> object address </address> </offer> </feed> -
NotADirectoryError at /admin/
I'm new in django, and I have a problem with The Django admin documentation generator I have install Docutils and all requirements specified in the documentation Now, the documentation is showing in my django admin: but the issue is when i want tu retrieve a link like LogEntry i got a following error: > NotADirectoryError at /admin/doc/views/frontend.views.index/ [Errno > 20] Not a directory: > '/usr/local/lib/python3.7/site-packages/docutils-0.16b0.dev0-py3.7.egg/docutils/writers/html4css1/template.txt' > Request Method: GET Request > URL: http://localhost:8008/admin/doc/views/frontend.views.index/ > Django Version: 2.2.1 Exception Type: NotADirectoryError Exception > Value: [Errno 20] Not a directory: > '/usr/local/lib/python3.7/site-packages/docutils-0.16b0.dev0-py3.7.egg/docutils/writers/html4css1/template.txt' > Exception > Location: /usr/local/lib/python3.7/site-packages/docutils-0.16b0.dev0-py3.7.egg/docutils/writers/_html_base.py > in apply_template, line 77 Python Executable: /usr/local/bin/python > Python Version: 3.7.4 Python Path: ['/webapp', > '/usr/local/lib/python37.zip', '/usr/local/lib/python3.7', > '/usr/local/lib/python3.7/lib-dynload', > '/usr/local/lib/python3.7/site-packages', > '/usr/local/lib/python3.7/site-packages/docutils-0.16b0.dev0-py3.7.egg'] > Server time: lun, 5 Aoû 2019 21:45:56 +0000 Here are my settings: # Application definition INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'django.contrib.admindocs', 'rest_framework_swagger', 'api.apps.ApiConfig', 'frontend.apps.FrontendConfig', 'dashboard.apps.DashboardConfig', ] 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', 'django.contrib.admindocs.middleware.XViewMiddleware' ] and my urls files look like: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('frontend.urls')), path('dashboard/', include('dashboard.urls')), path('admin/doc/', include('django.contrib.admindocs.urls')), path('admin/', admin.site.urls), path('api/', include('api.urls')), ] -
Ajax does not show any functionality in Django
I want to display an error screen for a new user who wants to retrieve a user name already taken using Ajax, but the project continues to run as if Ajax did not exist and django gives its own error. register.html {% extends "layout.html"%} {% load crispy_forms_tags %} {% block body %} <script> $("#id_username").change(function () { var username = $(this).val(); $.ajax({ url: '/ajax/validate_username/', data: { 'username': username }, dataType: 'json', success: function (data) { if (data.is_taken) { alert("A user with this username already exists."); } } }); }); </script> <body style = background-color:midnightblue;color:White;> <div class="row"> <div class="col-md-6 offset-md-3"> <h3>Register</h3> <hr style="background:white;"> <form method="post"> {% csrf_token %} {{form|crispy}} <br> <button type="submit" class ="btn btn-danger">Register</button> </form> </div> </div> </body> {% endblock body %} views.py def validate_username(request): username = request.GET.get('username') data = { 'is_taken' :p User.objects.filter(username__iexact=username).exist() } return JsonResponse(data) urls.py urlpatterns = [ path('login/',views.loginUser,name = "login"), path('register/',views.register,name = "register"), path('logout/',views.logoutUser,name = "logout"), path('panel/<str:username>',views.userPanel,name="userPanel"), path('ajax/validate_username/',views.validate_username,name="validate_username") ] -
django how to find the minimum value NOT in a field?
Assume that we have records with 1,2,4,5,6, ... in a field named Code in table Material. How can I write an orm to return 3 that is the minimum number not in the existing records? -
Add Multiple Placemarkers on Google Earth Fetching Address From SQL
I am trying to connect Google earth using python django framework and I want to add multiple place markers on Google earth based on the address stored in the database connected to django database by a single click on the User Interface. Is it possible to achieve this? Suppose I have 10 database records and we have a button on the UI which automatically places the markers on all the locations (addresses stored in the database). NA NA NA -
Django html forms get value from button
Shortly I am busy with the web framework Django, I have already implemented some small projects and wanted to try something bigger, but unfortunately I can not continue at one point and the search has not been promising. I would like to get displayed on a page single records from my database and by clicking this the server should get a feedback which of the displayed records was clicked. I currently use some CSS elements from Materialize, but that does not work as well as I would like. my example.html <head> </head> <body> {% block content %} <div class="row"> {% for data in persenal_data %} <form action= "{% url 'main:beispiel' %}" method="POST"> {% csrf_token %} <button class="col s10 m6 14" type="submit" > # value = data.id <div class="card"> <div class="card hoverable"> <div class="card-content"> <div class="card-title">{{data.id}} </div> </div> </div> </div> </button> </form> {% endfor %} </div> </body> and my views.py def build_reseption_page(request): if request.method == "POST": chusing_data = request.POST.get('value') return render(request=request, template_name='main/beispiel.html', context={"personal_data":personal_data}) else: return render(request=request, template_name='main/beispiel.html', context={"personal_data":personal_data}) I'd like to assign a variable by clicking the button # value = data.id, that this can be controlled in the views.py. -
Django: Check if record exists in two different states
I am using two models to build a chat system between users: class Chat(models.Model): created = models.DateTimeField(auto_now_add=True) class Participant(models.Model): chat = models.ForeignKey(Chat, on_delete=models.CASCADE, related_name='participants') sender = models.ForeignKey(CustomUser, on_delete=models.CASCADE) receiver = models.ForeignKey(CustomUser, on_delete=models.CASCADE) One record in the participants model represents the ability to send messages from the user sender to the user receiver. Thus, for a valid private chat between A and B, two records will exist, one with A as sender and B as receiver and vice versa. Since one user will always be the one starting the chat but the first participant record could be with A as sender or B as sender, I need to know if there's a clean and cheap way to check if both records exist when a user tries to initiate a chat, and return the chat id if it exists. How do I search for the existence of records (sender=A, receiver=B) and (sender=B, receiver=A) in the same query? -
Setting URL to use slug instead of ID
I want my URL to have slug instead of post ID in django This is my urls.py from django.urls import path, re_path from blog.views import( blog_post_detail_view, blog_post_list_view, blog_post_update_view, blog_post_delete_view,) urlpatterns = [ path('', blog_post_list_view), path('<str:slug>/', blog_post_detail_view), path('<str:slug>/edit/', blog_post_update_view), path('<str:slug>/delete/', blog_post_delete_view), ] models.py from django.shortcuts import render, get_object_or_404 from django.http import Http404 from .models import BlogPost def blog_post_list_view(request): qs = BlogPost.objects.all() template_name = 'blog_post_list.html' context = {'object_list': qs} return render(request, template_name, context) def blog_post_create_view(request): template_name = 'blog_post_create.html' context = {'form': None} return render(request, template_name, context) def blog_post_detail_view(request, slug): obj = get_object_or_404(BlogPost, slug=slug) template_name = 'blog_post_detail.html' context = {"object": obj} return render(request, template_name, context) def blog_post_update_view(): obj = get_object_or_404(BlogPost, slug=slug) template_name = 'blog_post_update.html' context = {"object": obj, 'form': None} return render(request, template_name, context) def blog_post_delete_view(): obj = get_object_or_404(BlogPost, slug=slug) template_name = 'blog_post_delete.html' context = {"object": obj} return render(request, template_name, context ) I want the url to read http://127.0.0.1:8000/admin/blog/blogpost/i-need-this/change/ instead of http://127.0.0.1:8000/admin/blog/blogpost/3/change/ -
I tried to create my first django project(using powershell) but failed to do so because of errors
I am new to django. I wanted to create my first sample project so I followed all the usual ways(as in youtube) and installed python 3.4,pip,django etc. When the environment was set I typed the below command in windows powershell django-admin startproject mysiteone and got the below syntax error message(See last para) My system uses Windows 7 OS. I was unable to find even the version of django i had installed. I dont know why. I gave these codes in powershell: django-admin startproject mysiteone python -m django --version Error message that I got as a result: Traceback (most recent call last): File "C:\Python34\lib\runpy.py", line 171, in _run_module_as_main "_main_", mod_spec) File "C:\Python34\lib\runpy.py", line 86, in _run_code exec(code, run_globals) File "C:\Python34\Scripts\django-admin.exe\_main_.py", line 5, in <module> File "C:\Python34\lib\site-packages\django\core\management\_init_.py", line 260 subcommands = [*get_commands(), 'help'] SyntaxError: can use starred expression only as assignment target -
Django-Haystack not returning exact query
I'm trying to fix my Django-haystack combined with Elasticsearch search results to be exact. The problem I have now is that when a user try for example, the "Mexico" query, the search results also returns deals in "Melbourne" which is far from being user-friendly. Anyone can help me to fix this problem? This is what I've tried so far but no good results: My forms.py from haystack.forms import FacetedSearchForm from haystack.inputs import Exact class FacetedProductSearchForm(FacetedSearchForm): def __init__(self, *args, **kwargs): data = dict(kwargs.get("data", [])) self.ptag = data.get('ptags', []) self.q_from_data = data.get('q', [''])[0] super(FacetedProductSearchForm, self).__init__(*args, **kwargs) def search(self): sqs = super(FacetedProductSearchForm, self).search() # Ideally we would tell django-haystack to only apply q to destination # ...but we're not sure how to do that, so we'll just re-apply it ourselves here. q = self.q_from_data sqs = sqs.filter(destination=Exact(q)) print('should be applying q: {}'.format(q)) print(sqs) if self.ptag: print('filtering with tags') print(self.ptag) sqs = sqs.filter(ptags__in=[Exact(tag) for tag in self.ptag]) return sqs My search_indexes.py import datetime from django.utils import timezone from haystack import indexes from haystack.fields import CharField from .models import Product class ProductIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.EdgeNgramField( document=True, use_template=True, template_name='search/indexes/product_text.txt') title = indexes.CharField(model_attr='title') description = indexes.EdgeNgramField(model_attr="description") destination = indexes.EdgeNgramField(model_attr="destination") #boost=1.125 link = indexes.CharField(model_attr="link") image = indexes.CharField(model_attr="image") … -
Send message to several groups using Django Channels
I'm building a chat app. I'd like to know: 1) If the way I'm currently implementing chat is incorrect / bad coding practice 2) How to send the message to several groups The base idea is the following: Each user connects to a specific channel (.../ws/), and is part of a specific group One group contains one user, and a user can only participate to one group When a user sends a message to another user, they also send a list of user IDs to whom the message should be transferred. The message is then sent to the different groups I'd like to send the message to those users in an efficient/scalable way. Below is the current way I'm implementing chat where the message is sent to one user (only 1 user is specified in data[userID]) def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) def receive(self, text_data): print('Websocket received info!') data = json.loads(text_data) # Send the message to the specified user self.send_channel_message(data[userID], data['message']) def send_channel_message(self, group_name, message): async_to_sync(self.channel_layer.group_send)( '{}'.format(group_name), # Specify intented group { 'type': 'channel_message', 'message': message } ) def channel_message(self, event): message … -
How to send django form data to flask api
I need to send data to a flask url but I keep getting the error working outside of request context. How do I send the data from the form to the url? views.py: def home(request): if request.method == 'POST': form = NameForm(request.POST) # logging.info(form) if form.is_valid(): logging.info("before req: " + str(jsonify(form))) response = flask_request.post('http://127.0.0.1:5000/vin/exists/', params=jsonify(form)) data = response.json() else: form = NameForm() return render(request, 'post/form.html', {'form': form}) -
How to store list data into the database using django
I have django model with one field calle tag_name and with the forms i am taking input from the user like below: Now in the views.py i got the input from the user whatever he passed and i have splited into the list like this: with this i am storing data in to the table like this: but i want to add these 2 name in to the table as seperated rows something like this: what can i do in the views.py file or in to the model to make this happen? -
How to Serve Django Application With Apache2 and Mod WSGI
I want to serve my Django applications using Apache2 and the mod_wsgi module. I have setup an Apache virtualhost at /etc/apache2/sites-available/mysite.confand I have made some configuration changes to WSGI at home/username/development/mysite/mysite/wsgi.py However, when I navigate to mydomain.com, I am being presented with the 500 Internal Server Error: The server encountered an internal error or misconfiguration and was unable to complete your request.. I am very new to server development and have never used Apache2 before so I am unsure as to where I have gone wrong in my configuration. Below you will find my virtualhost configuration file as well as my WSGI file. Additionally, I have provided the structure layout of my project directory in case this helps. Any help is greatly appreciated. directory structure >> home >> username >> development >> mysite >> mysite >> settings.py >> wsgi.py >> website >> static >> manage.py >> venv mysite.conf <VirtualHost *:80> ServerName mydomain.com DocumentRoot /home/username/development/mysite WSGIScriptAlias / /home/username/development/mysite/mysite/wsgi.py WSGIDaemonProcess mydomain.com processes=2 threads=15 display-name=%{GROUP} python-home=/home/username/development/venv/lib/python3.5 WSGIProcessGroup mydomain.com <directory /home/username/development/mysite> AllowOverride all Require all granted Options FollowSymlinks </directory> Alias /static/ /home/username/development/mysite/website/static/ <Directory /home/username/development/mysite/website/static> Require all granted </Directory> </VirtualHost> wsgi.py import os import time import traceback import signal import sys from django.core.wsgi import get_wsgi_application … -
Real time quiz web application using django
I need help in developing a real-time quiz application in Django. User(s) can participate in it according to to the admin, like a real-time competition. -
Generic View Not able to load and throws TemplateDoesNotExist error
I'm trying to use the Generic views in Django. This is a part of the tutorial on the official Django site. I've been at this problem for a few hours now and somehow the other answers on this website and others don't seem to solve my problem. The index.html file is working as localhost:8000/polls loads successfully but anything after that throws the TemplateDoesNotExist error. I don't know why when it tries to load a Generic view, it fails. I also tried removing the index.html file but still the Generic View failed to load I'll probably put up everything of concern here: My settings.py file: import os SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__)) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'v(wm5xfr8x3zr-5=vdezxz#_!74w=!^8l1#^r68-fm%%nqg)+1' DEBUG = True TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ) TEMPLATE_DIRS = ( "C:/Django/mysite/templates/polls/", ) ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'pankaj29', 'HOST': … -
How can a model have multiple keys with the same type of models as values?
I'm making an application and I should make a Model which have 2 keys that saves models of the same type. It's not easy to express in English so I will upload the image of the situation. In Food Pair Model ( or we can call it table I think ) I want to refer Food Model But I can't use ForeignKey or ManyToManyField. I don't know what database relation to use in this case and how to make it. What can I use for this case? -
How to update only field in drf
I'm trying to update a field of my model, im trying use patch for this, but i'm new to django rest and i think i'm having something wrong Im try use partial_update method but doesn't work. I want update status for canceled(canceled is in my enums.py ) This is part of my model class Aula(AcademicoBaseModel, permissions.AulaPermission): turma_disciplina = models.ForeignKey(TurmaDisciplina, models.PROTECT, related_name='lessons') data_inicio = models.DateTimeField(db_index=True) data_termino = models.DateTimeField() duracao = models.IntegerField(default=50) status = models.ForeignKey('Status', models.PROTECT, default=1) This is my view class CancelLessonView(generics.UpdateAPIView): serializer_class = serializers.AulaSerializer def patch(self, request, *args, **kwargs): lesson = self.kwargs.get('id') instance = models.Aula.objects.get(id=lesson) status = models.Status.objects.get(id=enums.StatusEnum.CANCELLED) instance.status.id = enums.StatusEnum.CANCELLED instance.status.name = status.name instance.status.color = status.color instance.status.ignore_in_attendance_report = status.ignore_in_attendance_report instance.status.allow_attendances = status.allow_attendances instance.status.allow_activities = status.allow_activities serializer = serializers.AulaSerializer(data=request.data, partial=True) serializer.is_valid(raise_exception=True) self.perform_update(serializer) instance.save() return Response(serializer.data) -
how to play audio using javascript , HTML , AJAX
I am trying to embed the audio player in my website . The requirement of this is when the user selects other page the audio should still play in the background unless user pause for it. I guess the terminology for this is Persistence audio player . not sure though. Can anyone provide some example how to achieve this one? I guess I have to use AJAX for this , if I am not wrong. Thank you -
How to only display one part of a class and iterate through it with a button
So basically I am basically trying to output one scene at a time in a story app. I have created a model that has a Story, Scene, and Choices. The Story has a title, and the scenes are related to the story via foreign-key, and the choices are related to the scenes via foreign-key. After finally being able to display all the scenes to their designated Story, and choices to their designated scene How would I be able to 1). Show only one scene at a time? Because the problem I'm facing is looping through them but it displays all the scenes and their possible choices under them but I would not like the user to see the next scene until they have answered so that when they hit submit if it has x boolean then I want it to either stop or continue the story depending on their answer 2). How do I show the choice they chose displayed with the next scene? I am really new to Django and trying my best to use class views as I've heard they are best in the long run of things but I don't understand how I would in this case? … -
How can I autofill author with a model form (video upload)
I need to tie the user to their post but 'author' is not included in the fields of the video upload form so I can't access the field when I save the form. When I add 'author' to the fields it gives a drop down box. (users shouldn't be able to post as anyone but themselves) I tried just listing the fields individually like so {{form.title}} to keep the author field but not show it to the user, it showed anyway. In the 'author' field of the VideoPost model I've tried changing out the null=True for these variants on default default=None, default=0, default='None', default=User, default=User.id where User = get_user_model() When I used default='None' the author dropdown box had the current users name in it, but still allowed a choice, when I tried to post it I got ValueError: invalid literal for int() with base 10: 'None' Also, in the views.py, I tried form = VideoPostForm(request.user,request.POST or None, request.FILES or None) and got CustomUser object has no .get() attribute and that was caused by form.save() I feel like this might be obvious to someone else but I've been staring at this code for a while now to figure it out.(a couple …