Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there anyway in django to create the form such that when users select on one choice it will show another set of choice that users can select on
I want to create the form such that when users select on one choice it will show another set of choices that users can select on (or show text field that user can write in). For example, if I have a form Use geographical feature Yes No When user select yes it will show another set of choices under "yes" Use geographical feature Yes randomize fixed input No Is there any possible way to implement in django and how to embed it in django html template? I am quite new to the web-dev and django. So, I am not quite sure what to look for and Googling hasn't yielded me the answer I am looking for. -
Suggestions for splitting up a Django model of 1000+ fields
I am looking for suggestions on how to deal with a database table that has 1000 or more columns and I am tying to translate it into one or many Django models. The data also needs to be filtered through API calls within the URL. Every field needs to be able to filter the rest of the data. I have come up with a few solutions and would like input or resources related to them: Just have a model with 1000+ fields - This seems like it would be a nightmare to maintain and would require a lot of brute force coding but would likely work fine if data was selectively returned. Use a JSON field to store all less frequently accessed data - The issue here would be difficulty in filtering the data using Django Filters. Split data into related models connected by One-to-One relationships, as I understand this cuts down on join operations. - This would seem to require more coding than the first option but would be more maintainable. Does anyone have any information or resources on dealing with database tables of this size? -
Django form saves and fetches <QuerySet object> instead of values
I have a simple Django 3.1.0 app I need to create in order to assign Tasks with Tags (or assign tags into tasks). Model class Task(models.Model): user = models.CharField(max_length=33) time = models.DateTimeField(auto_now_add=True) task = models.CharField(max_length=500) tags = models.CharField(max_length=100, default="None", null=True) class Tag(models.Model): tag = models.CharField(max_length=30, default="No Tag") members = models.ManyToManyField('Task', related_name="tag") class Meta: verbose_name = "tag" verbose_name_plural = "tags" view def main(request): model = Task.objects.values().all() tags = Tag.objects.values().all() form = TaskForm() con = {'context': list(model), 'form': form, 'tags': list(tags)} if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect('/') else: form = TaskForm() return render(request, "tasks.html", con) form class TaskForm(ModelForm): class Meta: model = Task fields = ['user', 'task', 'tags'] template_name = 'tasks.html' tags = ModelMultipleChoiceField( queryset= Tag.objects.all(), widget=CheckboxSelectMultiple(), required=False, ) task_form <form method="post" class="form"> {% csrf_token %} {{form}} <input type="submit" value="Save"> </form> This returns in the tags list the items listed as: Tag object (1) Tag object (2) And when it saves when i press submit, it fetches in a table (in another template), the values saved in the text of <QuerySet [<Tag: Tag object (2)>]> That's how it stores them in the database. I have managed to extract the values as they are ('tag1','tag2') and send … -
Email activation link issue in Django 3.1.3
Well, I decided to implement an account authentication system by sending an activation link to the email of the user who just registered and here are the views and the message sent def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) mail_subject = 'Activate your blog account.' message = render_to_string( 'users/email_template.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), } ) to_email = form.cleaned_data.get('email') email = EmailMessage(mail_subject, message, to=[to_email]) email.send() return HttpResponse('Please confirm your email address to complete the registration') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) return HttpResponse('Thank you for your email confirmation. Now you can login account.') else: return HttpResponse('Activation link is invalid!') Token Generator class: from django.contrib.auth.tokens import PasswordResetTokenGenerator from six import text_type class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( text_type(user.pk) + text_type(timestamp) + text_type(user.is_active) ) account_activation_token = TokenGenerator() The template with the message: {% autoescape off %} Hi {{ user.username }}, Please click on the link to confirm … -
is there a way to create superuser for django apps on heroku without using CLI?
I changed my db of my app on heroku to not use the sqlite db that is the default for django app, to use the heroku postgres database. however, I want to login to my admin portal on my heroku app, but i am not sure how to create a superuser. Also, is there a way to push my local db to my heroku db? I have been deploying through github (not using the heroku CLI, so I was wondering if there was a way without using the CLI). if there isn't a way without using the heroku CLI, could someone tell me how I would init the heroku git repository, considering the fact that I already have a GitHub repository that I have been using (I am not great with git). this is my settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } import dj_database_url db_from_env = dj_database_url.config(conn_max_age=600) DATABASES['default'].update(db_from_env) -
How to handle a site wrapper and in Django templating?
I have a Wagtail site with the following structure: <html> <head> </head> <body> <div id="site-wrapper"> <div id="site-canvas"> <div id="site-navigation"> </div> <div id="site-mobile-navigation"> </div> <div id="content"> </div> </div> </div> </div> </body> </html> I would like to use the {% extends "base.html" %} command to utilize the above HTML structure within a site wide template, but I'm not sure how to handle extending exclusively within the the <div id="content"> element. The hope is that the navigation, header, body, etc., could all be placed in a template but that I could begin the Wagtail pages starting within the 'content' div. -
Django ManyToManyField upload multiple files getting error NoneType
I want to upload multiple file in Django. The code below is getting 'NoneType' object is not iterable. I don't understand How can i make files iterable and save in database. i have m2m field. i think i need to create FileModel before FileUploadModel. I would be grateful for any help. MODELS class FileModel(models.Model): filename = models.FileField(upload_to='files/') class FileUploadModel(models.Model): file = models.ManyToManyField(FileModel, blank=True) FORMS from .models import FileUploadModel class AForm(forms.ModelForm): file = forms.FileField(label='Select a file to upload', widget=forms.ClearableFileInput(attrs={'multiple': True}), required=False) def __init__(self, *args, **kwargs): super(AForm, self).__init__(*args, **kwargs) class Meta: model = FileUploadModel fields = '__all__' VIEWS def uploading_view(request): form = AForm(request.POST, request.FILES) if request.method == "POST": if form.is_valid(): a = form.save() # Here you have the a model already created files = request.FILES.getlist('file') # 'file' is the name of the form field. for f in files: a.file.create(filename=f) # Here you create a "b" model directly from "a" model context = { 'form': form } return render(request, 'uploading.html', context) -
My css changes are not getting reflected when i run my website
In my directory i have de following: -Proyecto -proyecto -static -css styles.css -images -tienda in my settings.py file i already added my STATICFILES_DIRS: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] And in my template called "tienda.html" i have the following: {%load static%} <link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}"> <h3>TIENDA</h3> when i run my website with my localhost, no css changes are reflected. I already tried deleting de cache from the explorers but still i can´t see any changes. -
Django views and HTML form
I have created a form in HTML and I want to bind it to a model, but I do not know how to make it possible to select a form from the database data by the type of a drop-down list. (for example, the name of the doctor and patient that should already be stored in the database.) When I do this through creating a form through django, everything works out, but I'm interested in HTML I get error : ValueError at /create_appointment/ Cannot assign "'patient'": "Appointment.patient" must be a "Patient" instance. models.py class Appointment(models.Model): time_appointment = models.DateTimeField() patient = models.ForeignKey( Patient, related_name='patient_to_appointment', null=True, on_delete=models.SET_NULL) doctor = models.ForeignKey( Doctor, related_name='doctor_appointment', null=True, on_delete=models.SET_NULL) complaint = models.CharField(max_length=50, null=True, blank=True) views.py def create_appointment(request): if request.method == 'POST': datetime = request.POST['datetime'] patient = request.POST['patient'] doctor = request.POST['doctor'] service = request.POST['service'] appointform = Appointment( time_appointment=datetime, patient=patient, doctor=doctor, complaint=service) appointform.save() return redirect('/appointment') return render(request, 'main/f_appointment.html') html <body> <div class="text-center mt-5"> <form style="max-width: 480px; margin: auto" method="post"> {% csrf_token %} <p class="hint-text mb-3">Please sign in</p> <label class="sr-only" for="datetime"></label> <input type="datetime-local" name="datetime" class="form-control" placeholder="гггг-мм-дд чч:мм:сс время и дата записи" required autofocus /> <label for="patient" class="sr-only"></label> <input type="text" name="patient" class="form-control mt-2" placeholder="пациент" /> <label for="doctor" class="sr-only"></label> <input type="text" name="doctor" … -
Django Whitenoise causes error collecting static
When I run collectstatic on my Django site, I always get an error. This is my settings.py: """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 3.1.1. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES_DIRS = os.path.join(BASE_DIR, 'templates') STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'not showing it here' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'news', 'writers', ] INSTALLED_APPS += ('django_summernote', ) 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', 'whitenoise.middleware.WhiteNoiseMiddleware', 'news.middleware.TimezoneMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_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', 'news.context_processors.common_variables' ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { … -
Create a like button for blog posts in my Django?
I've been trying to create a like button for my blog posts in my Django blog but I can't figure out how to create one because it contain Integer . When the user clicks on the like button . The like button will increase and it will display near the post. This is my like module: class Post(models.Model): title = models.CharField(max_length=225) post_image = models.ImageField(null=True, blank=True, upload_to="images/") author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() post_date = models.DateField(auto_now_add=True) def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('post-detail', args=(str(self.id)),) Thanks in advance -
Django extensions shell_plus --lab not working
I've been trying to use ./manage.py shell_plus --lab command but i keep getting following error: ... File "/home/user/.local/share/virtualenvs/project-MorsWGAo/lib/python3.8/site-packages/django_extensions/management/commands/shell_plus.py", line 556, in handle runner() File "/home/user/.local/share/virtualenvs/project-MorsWGAo/lib/python3.8/site-packages/django_extensions/management/commands/shell_plus.py", line 303, in run_jupyterlab self.run_notebookapp(app, options) File "/home/user/.local/share/virtualenvs/project-MorsWGAo/lib/python3.8/site-packages/django_extensions/management/commands/shell_plus.py", line 237, in run_notebookapp app.initialize(notebook_arguments) File "/home/user/.local/share/virtualenvs/project-MorsWGAo/lib/python3.8/site-packages/jupyterlab/labapp.py", line 732, in initialize super().initialize() File "/home/user/.local/share/virtualenvs/project-MorsWGAo/lib/python3.8/site-packages/jupyter_server/extension/application.py", line 403, in initialize raise JupyterServerExtensionException(msg) jupyter_server.extension.application.JupyterServerExtensionException: This extension has no attribute `serverapp`. Try calling `.link_to_serverapp()` before calling `.initialize()`. I'm using pipenv this would be potentially relevant parts of my Pipfile: [[source]] url = "https://pypi.org/simple" verify_ssl = true name = "pypi" [scripts] dev = "./scripts/dev.sh" [requires] python_version = "3.8" [pipenv] allow_prereleases = true [packages] Django = "~=3.0.0" ... django-extensions = "*" ... [dev-packages] flake8 = "*" autoflake = "*" bpython = "*" epc = "*" importmagic = "*" ipdb = "*" ipython = "*" pyls-black = "*" pyls-isort = "*" coverage = "*" werkzeug = "*" jupyterlab = "*" I'd really appreciate any help with this. Thx in advance. -
Moving password validation errors for Django UserCreationForm, from password2, to password1
I've got a Django form class, that inherits from the built-in UserCreationForm. I'm working on submitting the form using AJAX, and returning the bound form (including errors) as rendered HTML if it doesn't validate. Something puzzling me is that the errors relating to the password (e.g. too short, common password...) appear for the password2 / confirmation field. Here's a screenshot of the default behaviour: From a UX perspective I feel as though it would be more useful for the errors to appear for the first password field in the form, so users can adjust that one, then confirm it by typing it again below. I've noticed that in UserCreationForm, clean_password2(), doesn't actually validate the password, it just checks that password1 and password2 match. Then in the _post_clean() method, password2 is validated, and any errors are added to that field. In my attempt to change it, I have overridden _post_clean() as follows: def _post_clean(self): super(forms.ModelForm, self)._post_clean() password = self.cleaned_data.get('password1') if password: try: password_validation.validate_password(password, self.instance) except forms.ValidationError as error: self.add_error('password1', error) I don't want to call super, and have it validate and send errors to password2, so I am calling the post_clean method of the grandparent (ModelForm) instead (I think!), to not … -
Django Template curly brackets inside curly brackets
{% if hosts %} <div class="row"> {% for host in hosts %} {% if host.type_of == "Backend" %} <div class="col-sm-3">{{ host.type_of }}</div> {{ headers.{{ forloop.counter0 }} }} {% endif %} {% endfor %} </div> {% endif %} I am sending arrays, hosts and headers from views to my template, I need to get element of header with the current index (getting the header[i]) Error says Could not parse the remainder: '{{ forloop.counter0' from 'headers.{{ forloop.counter0' Can't seem to find any examples regarding to this. How can I achieve what I want ? -
BooleanField is not showing ( accessing ) in template
I am building a BlogApp and I built a comment disabled system, I did everything BUT Boolean Field's True or False options are not Accessing in Template. views.py This is the view of DetailView of Post. I did in it like :- If user tick Boolean Field while creating post then the comment form will not be seen. BUT..... def detail_view(request,id): data = get_object_or_404(Post,id=id) comments = data.comments.order_by('-created_at') new_comment = None comment_form = CommentForm(data=request.POST) if Post.allow_comments == True : if request.method == 'POST': if comment_form.is_valid(): comment_form.instance.post_by = data comment_form.instance.commented_by = request.user comment_form.instance.active = True new_comment = comment_form.save() return redirect('mains:detail_view',id=id) else: comment_form = CommentForm() context = {'data':data,'comments':comments,'new_comment':new_comment,'comment_form':comment_form} return render(request, 'mains/show_more.html', context ) new_post.html This is the view for Create new post. It will show the BooleanField while creating the Post. def new_post(request): """Add a new TOPIC .""" if request.method != 'POST': #No Data Submitted ; Create a blank form. form = PostForm() else: #Post data submitted ; process data. form = PostForm(request.POST,request.FILES) new_post = form.save(commit=False) new_post.post_owner = request.user new_post.save() return redirect('mains:posts') context = {'form':form} return render(request, 'mains/new_post.html', context) detail.html The Problem is in this Template {% if comment_form.allow_comments == True %} <br> <form method="post"> {{ comment_form.as_p }} {% csrf_token %} <p><input type="submit" … -
Django 3.1.5 serving static files with Heroku
I'm having problems trying to get my Django web app on Heroku to pick up the static CSS file. Lots of the answers online already seem to refer to an older version of Django, but I've spent hours researching and still can't figure it out :( Help is appreciated! layout.html {% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="{% static 'mainapp/styles.css' %}"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> {% if user.is_authenticated %} <a href="{% url 'logout' %}">Log out</a> {% else %} <a href="{% url 'login' %}">Log in</a> <a href="{% url 'register' %}">Register</a> {% endif %} {% block body %} {% endblock %} </body> </html> Info from Heroku which I think is relevant 2021-01-23T18:07:29.675104+00:00 app[web.1]: Not Found: /static/mainapp/styles.css 2021-01-23T18:07:29.675580+00:00 app[web.1]: 10.101.178.182 - - [23/Jan/2021:18:07:29 +0000] "GET /static/mainapp/styles.css HTTP/1.1" 404 179 "https://XXXXXX-XXXXXX-XXXXX.herokuapp.com/register" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36" 2021-01-23T18:07:29.676045+00:00 heroku[router]: at=info method=GET path="/static/mainapp/styles.css" host=XXXXXX-XXXXXX-XXXXX.herokuapp.com request_id=bb1c9f74-b21b-456e-96ca-b248d7ce5cd2 fwd="XX.X.XXX.XXX" dyno=web.1 connect=0ms service=6ms status=404 bytes=418 protocol=https base.py (settings) """ Django settings for myproject project. Generated by 'django-admin startproject' using Django 3.1.5. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os from pathlib import Path … -
Using ```localStorage``` to store dynamically created buttons in Javascript
My goal is to have the user enter values which then generates a button. They should be able to continuously enter values and new buttons should be created following each entry. My current code allows for the creation of one button, but as soon the form is submitted, the page refreshes and the button is gone. How can I store them so that they stay on the page? My code: <script> var counter = 0; function createButton(){ var x = document.createElement("BUTTON"); x.className = "second"; var name = document.querySelector("#id_goal").value; var t = document.createTextNode(name); x.appendChild(t); document.getElementById("space_holder").appendChild(x); var insideclass = document.getElementsByClassName("second"); insideclass[counter].innerHTML = `<input type="button" onclick="location.href='/inside_goal'" value="${name}"/>`; counter = counter+1; }; </script> <h1 id = "home_header" style = "font-family: optima; text-align: center"> Nancy Dong </h1> <div id = "enter.goal"> <form id = "subBox" onsubmit="createButton();" method="post"> {% csrf_token %} {{ form }} <input type="submit", value = "Enter Goal"> </form> </div> <div id = "space_holder" style = "top: 50px; left: 50px;"> </div> Django Views.py class NewGoalForm(forms.Form): goal = forms.CharField(label="new goal") def index(request): return render(request, "index.html",{ "form": NewGoalForm() }) -
Concatenate Javascript for variable with django variable
Good afternoon, I have a javascript block that I would like to iterate and get a Django variable based on the index. How can I do this in a javascript block on django template? Example: var data = google.visualization.arrayToDataTable([ ['Descrição', 'Quantidade'], ['Concluídas', parseFloat("{{1_seller.seller_reputation.transactions.completed}}")], ['Canceladas', parseFloat("{{1_seller.seller_reputation.transactions.canceled}}")] ]); var options = { title: 'Transações ({{1_seller.seller_reputation.transactions.total}})', pieHole: 0.5, }; var chart = new google.visualization.PieChart(document.getElementById('1_transactionschart')); chart.draw(data, options); then the idea is to iterate over "1_", "2_", "3_" and goes on. How can I make this for in javascript and get the django variable? Regards, Bernardo -
Django: How to render data in tamplate from another template on button click
I would like to ask for help for my following issue: I have a template on the "Customer" side and template on the "Staff" side where both are in different django apps. Now..from Customer page I am via Ajax (button click) sending data to two different views (Customer and Staff) and saving objects to database . It is working but as you can see the Staff page will render data from Customer only When Loading the page. How I can render real time data on Staff page every time Customer will press the button either from view or from database? I believe I should use Django Channels for this purpose and I actually manage to get to work a test Chat room but I have no idea how I could implement it for my case. I am not an advance developer as you can see. Thank you in advance. -
Bootstrap Tooltip with HTML title attribute not working
I am trying to add a Bootstrap tooltip with 'data-html' attribute as true to a card as a span element using plain JavaScript. Some background Information I am using Django for the back-end and plain JavaScript for the front-end. Posts are added after the DOM content is loaded. A function addPost creates a card element where the post content and likes are displayed, near the like button I am trying to display the number of likes and with the help of a tooltip I want to display the names of the people who like that particular post. Here's the Layout.html file where the Bootstrap CSS and JS links are placed as well as the JS file of my project: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}Social Network{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="{% static 'network/styles.css' %}" rel="stylesheet"> <script src="{% static 'network/index.js' %}"> </script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"> </script> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-primary"> <a class="navbar-brand" href="#">Network</a> <div> <ul class="navbar-nav mr-auto"> {% if user.is_authenticated %} <li class="nav-item"> <a class="nav-link" onclick="load_postsbox({{user.username}})"><strong>{{ user.username }}</strong></a> </li> {% endif %} <li class="nav-item"> <a class="nav-link" id="all-posts">All Posts</a> </li> {% if user.is_authenticated … -
Can't refresh page in React-django app deployed in Heroku
I'm trying to deploy an application that I have made using the Heroku platform. I have followed this tutorial to deploy the application and everything seems to work well until the page is refreshed (whether I refresh it manually, or the internal code has to refresh it). Everything works fine on my local computer. The error: Not Found The requested resource was not found on this server. is displayed on the deployed app when I try to refresh the page. I'm guessing it's a problem with my "views.py" file or "settings.py" file. Here there are: ## views.py from django.views.generic import TemplateView from django.views.decorators.cache import never_cache # Serve Single Page Application index = never_cache(TemplateView.as_view(template_name='index.html')) ## settings.py # Application definition INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', # < As per whitenoise documentation 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'hola.apps.HolaConfig', 'ckeditor', 'ckeditor_uploader', ] CKEDITOR_UPLOAD_PATH = "uploads/" MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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 = 'backend.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'build')], '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 = 'backend.wsgi.application' # # Database # # https://docs.djangoproject.com/en/3.1/ref/settings/#databases # DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': … -
Django/Python: update item in list
Hey so I am new to django/python and I want to create a to-do-app. I already have the basic structure, I can add a task, it is shown in my list and I can delete it. So I already have the C, R, and D from the CRUD features :-) Now I want to be able to update a task that is already in my list. So e.g. if I have a task called "laundry" I want to be able to click on it and change it to "do laundry" and save it. Or something like that. I have no idea how to to this or if it is possible. Maybe you can give me some inspiration (I want to do it myself so I don't need full code solutions). I am just kinda stuck and need somewhere to start... Thanks a lot in advance! -
local variable 'comment_form' referenced before assignment
I am building a BlogApp and I built a feature that if user disable comments ( through Boolean Field ) then the comments will be disabled. BUT i am stuck on an Error. When i open browser then it is showing me :- local variable 'comment_form' referenced before assignment views.py def detail_view(request,id): data = get_object_or_404(Post,id=id) comments = data.comments.order_by('-created_at') new_comment = None if Post.allow_comments == True: if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): comment_form.instance.post_by = data comment_form.instance.commented_by = request.user comment_form.instance.active = True new_comment = comment_form.save() return redirect('mains:detail_view',id=id) else: comment_form = CommentForm() else: print("Comments are Disabled") context = {'data':data,'comments':comments,'new_comment':new_comment,'comment_form':comment_form} return render(request, detail.html', context ) models.py class Post(models.Model): creater = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) date_added = models.DateTimeField(auto_now_add=True,null=True) description = models.CharField(max_length=10000,default='') allow_comments = models.BooleanField(default=False) detail.html <div class="container"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} </div> <div class="col-6"> {{ form.description }} </div> </div> <br> {{ form.allow_comments }}<p>Allow Comments</p> <br> <br> <button type="submit">Add this Post</button> <button type="reset" value="reset">Reset Everything</button> </form> </div> I don't know . What am i missing in this. Any help would be appreciated. Thank You in Advance -
How can i save Multiple items in database using FileField in Django?
i want to upload multiple files from Django FileField. The code below upload single file instead of multiple files. i also define for loop for file data but i don't understand how can i files save in database? I would be grateful for any help. Views class NewsCreateView(CreateView): form_class = ArticleForm template_name = 'create.html' success_url = '/' def form_valid(self, form): form.instance.author = self.request.user for f in self.request.FILES.getlist('file_data'): # file_data it's an a Attribute instance = form.file_data = f instance.save() return super().form_valid(form) -
How do I change the 'name' HTML attribute of a Django Form field?
I have a Django 3.0 form # forms.py class SignupForm(UserCreationForm): email = forms.EmailField() This renders as the HTML element <input type="text" name="email" required id="id_email"> Is there a way to change the 'name' attribute? The widgets documentation suggests that either of these might work: # forms.py class SignupForm(UserCreationForm): email = forms.EmailField( widget = forms.TextInput( attrs = {'name': 'email_address'} ) ) or # forms.py class SignupForm(UserCreationForm): email = forms.EmailField() email.widget.attrs.update({'name': 'email_address'}) but both render with two name attributes; the first one isn't replaced: <input type="text" name="email" name="email_address" required id="id_email"> Is there a straightforward method of changing the name attribute? I've found a couple of related previous posts, but the questions and answers tend to be old (Django 1.0-era) and more convoluted than this process ought to be. I'm hoping that newer versions have a simpler solution.