Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use date widget in django-import-export?
I'm new to programming so please bear with me in case I ask silly questions. I'm working on my first project which will gather data from Excel file. I'm trying django-import-export for that purpose but ran into a problem with date containing field. As far as I could understand searching this issue I need to use Date widget, cause it basically reads it as string while importing. But I couldn't find any example where this widget is used so I can see it's syntax. The model I'm working on is shown below. Hope some of you can help me on this. Thanks. from django.db import models from import_export.admin import ImportExportModelAdmin from import_export import widgets class Employee(models.Model): name = models.CharField(max_length=200) badge = models.CharField(max_length=15) start_date = models.DateField(auto_now=False, auto_now_add=False, blank=False, null=True,widget=widgets.DateWidget(format=None)) end_date = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True) status = models.BooleanField(choices=( (True, 'Active'), (False, 'Inactive') ), default=True) job = models.ForeignKey(Matrix, on_delete=models.CASCADE, blank=True, null=True) location = models.ForeignKey(Location, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return str(self.badge)+ str(" - ") + str(self.name) class Meta: ordering=('name', 'badge', 'start_date', 'status',) verbose_name='Employee' verbose_name_plural='Employees' -
Send email using django without a settings file
Is it possible to do something like the following using the utility django sendmail? >>> import os >>> from django.core.mail import send_mail >>> os.environ['EMAIL_HOST'] = 'smtp.sendgrid.net' ... etc. >>> send_mail( ... 'Subject here', ... 'Here is the message.', ... 'from@example.com', ... ['to@example.com'], ... fail_silently=False, ... ) django.core.exceptions.ImproperlyConfigured: Requested setting EMAIL_BACKEND, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. If so, how could I do this? -
Django admin page. When i run the server everything will be fine, but when i try log into the admin page i will lose my connection
Am getting back the last line after i navigate to the 127.0.0.1:8000/admin the browser message This site can’t be reached127.0.0.1 refused to connect. Try: Checking the connection Checking the proxy and the firewall ERR_CONNECTION_REFUSED my terminal message "C:\Program Files\JetBrains\PyCharm 2019.2\bin\runnerw64.exe" C:\Users\UCHE\PycharmProjects\blog\venv\Scripts\python.exe C:/Users/UCHE/PycharmProjects/blog/manage.py runserver 8000 Performing system checks... Watching for file changes with StatReloader System check identified no issues (0 silenced). March 16, 2020 - 22:15:50 Django version 3.0.4, using settings 'blog.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [16/Mar/2020 22:16:26] "GET / HTTP/1.1" 200 19 Not Found: /favicon.ico [16/Mar/2020 22:16:28] "GET /favicon.ico HTTP/1.1" 404 2136 [16/Mar/2020 22:16:34] "GET /admin/ HTTP/1.1" 302 0 [16/Mar/2020 22:16:34] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 1913 [16/Mar/2020 22:16:35] "GET /static/admin/css/base.css HTTP/1.1" 304 0 [16/Mar/2020 22:16:35] "GET /static/admin/css/login.css HTTP/1.1" 304 0 [16/Mar/2020 22:16:35] "GET /static/admin/css/responsive.css HTTP/1.1" 304 0 [16/Mar/2020 22:16:35] "GET /static/admin/css/fonts.css HTTP/1.1" 304 0 [16/Mar/2020 22:16:36] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 304 0 [16/Mar/2020 22:16:36] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 304 0 [16/Mar/2020 22:16:49] "POST /admin/login/?next=/admin/ HTTP/1.1" 302 0 Process finished with exit code -1 -
Django queries: When to use ' '
I just don't get why sometimes have to use something like Model.objects.filter('fieldname'=foo) and sometimes it is okay to use just fieldname without the ''. Could you explain that to me, please? -
Django page update without refresh
I have a small Django project consisting of one app. I am very very new to Django and have run into a problem. I have an app that is a webpage with a question posed and a form that must have input. Once the button is pressed to submit the form, I would like to update the page without refreshing. I have heard AJAX is a good way to handle this but I have not been able to find any examples working with just forms. My Forms from django import forms from . import models class AnswerForm(forms.Form): answer = forms.CharField(label='Answer', required=True, max_length=500) def save(self): answer_instance = models.Answer() answer_instance.answer_txt = self.cleaned_data["answer"] answer_instance.save() return answer_instance My Models from django.db import models from django.forms import ModelForm class Riddle(models.Model): riddle_txt = models.CharField(max_length=900) def __str__(self): return self.riddle_txt class Answer(models.Model): answer_txt = models.CharField(max_length=900) def __str__(self): return self.answer_txt My Views from django.http import JsonResponse from django.shortcuts import get_object_or_404, render from django.template import loader from .models import Riddle, Answer from . import forms # Create your views here. def index(request): form = forms.AnswerForm() if request.method == "POST": form = forms.AnswerForm(request.POST) if form.is_valid(): form.save() form = forms.AnswerForm() else: form = forms.AnswerForm() riddle_list = Riddle.objects.all() answer_list = Answer.objects.all() form = … -
Why i create two records at once using django-bootstrap-modal-forms
I'm using django-bootstrap-modal-forms. My forms.py: class UserAppForm(BSModalForm): class Meta: model = UserApp fields = ('app', 'app_type') In view, in order to attach current user, i override form_valid(): class AppCreateView(BSModalCreateView): template_name = 'apps/app_create.html' form_class = UserAppForm success_message = 'Success: App was created.' success_url = reverse_lazy('dashboard') def form_valid(self, form): app = form.save(commit=False) profile = Profile.objects.get(user=self.request.user) app.profile = profile app.save() return redirect(self.success_url) But, if i try to create UserApp, i get two instances at once. Where is my mistake? -
How to get image file from azure blob storage in django?
I habe build an app using django rest framework,react and deployed it to azure container service. I can successfully upload image on azure blob storage.but i need to process the image by a AI model to predict a result. I can easily get the image data from local database by 'instance.Image.path'. But when i connect the database to azure database then i cant get the image file.it throws an error called 'this backend doesn’t support absolute path'.so i changed the image.path to image.name but it always get the image name not the image file.I actually need the image file to process.what is the solution for azure service to get the image file. -
Can't access to django models with an external script
I have created a Django project with a series of tables (models) using postgresql. The thing, is that one of them I want to be able to access it also from outside the Django project, because from Django I simply want to see its content, but with an external script I want to insert the data. The problem I have is that when I try to access any of the tables created in django from an external script, the windows terminal, or even the program that postgresql offers. It tells me that the table does not exist. What am I leaving or doing wrong? The problem I have is that when I try to access any of the tables created in django from an external script, the windows terminal, or even the program that postgresql offers. It tells me that the table does not exist. What am I leaving or doing wrong? Below I show a screenshot with the tables I have and how it gives me an error. As you can see I have the ability to see all the tables, but then it doesn't let me select any of them. I have tried everything with lowercase and neither, … -
Modify certain sectioins of the django admin page in order to display user posted content
I'm attempting to allow users of my site to send in post suggestions, etc., which will be viewable only by admins through a read-only view on the Django administration page. Previously, when i ran all of this it returned: TypeError: __init__() takes 1 positional argument but 2 were given which I believe is related to this: # forms.py from django import forms class Form(forms.Form): username = forms.ChoiceField() message = forms.CharField() def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(Form, self).__init__(*args, **kwargs) I'm trying to load the desired content with this in messages.html: # messages.html {% for form in all_forms %} {{ form.username }} said: <br /> {{ form.message }} {% endfor %} This is my admin.py file: # admin.py from django.contrib.admin import AdminSite from django.http import HttpResponse from .models import Post from django.views import generic from .forms import Form from django.contrib.auth.urls import urlpatterns from django.shortcuts import render class MyAdminSite(AdminSite): def get_app_list(self, request): app_list = super().get_app_list(request) app_list += [ { "name": "Communication", "app_label": "communication", "models": [ { "name": "Messages", "object_name": "messages", "admin_url": "/admin/messages", "view_only": True, } ], } ] return app_list def get_urls(self): from django.urls import path urlpatterns += [ path('messages/', self.admin_view(self.Messages)) ] return urlpatterns class Messages(generic.ListView): def get(self, request, *args, **kwargs): … -
Error with Django formset when using ajax
I am trying to get an formset back with ajax but I get this error. I have {{ form.management_form }} and in my ajax, I am sending the management_form with the data back. Can someone see what I am doing wrong? ManagementForm data is missing This is my ajax: function plot() { $.ajax({ url: '', method: "POST", async: true, data: { 'form-0-new_mwant': $('#id_form-0-new_mwant').val(), 'form-0-new_rwant': $('#id_form-0-new_rwant').val(), 'form-0-new_fwant': $('#id_form-0-new_fwant').val(), 'form-1-new_mwant': $('#id_form-1-new_mwant').val(), 'form-1-new_rwant': $('#id_form-1-new_rwant').val(), 'form-1-new_fwant': $('#id_form-1-new_fwant').val(), 'form-TOTAL-FORMS': $('#id_form-TOTAL-FORMS').val(), 'form-INITIAL-FORMS': $('#id_form-INITIAL-FORMS').val(), 'form-MIN_NUM_FORMS': $('#id_form-MIN_NUM_FORMS').val(), 'form-MAX_NUM_FORMS': $('#id_form-MAX_NUM_FORMS').val(), csrfmiddlewaretoken : $('input[name=csrfmiddlewaretoken]').val() }, dataType: 'json', beforeSend: function(){ $('.loader').css("display", "block"); $('#plot_image').css("display", "none"); }, success: function(json){ complete: function(){ }, error: function(xhr,errmsg,err){ console.log("error"); console.log(xhr.status + ": " + xhr.responseText); } }); }; This is my template: <div id="add_user_form"> <form action="{% url 'eci:index' %}#additional_user_form" method="POST" id="post-add-user-form"> {% csrf_token %} {{ addition_user_form.management_form }} {%for form in addition_user_form %} <span class="add_user_text"> Add More Point To Plot: </span> {{ form }} {% endfor %} </form> </div> This is from my view: from django.forms import formset_factory from .forms import AdditionalUserForm def get_variables(request): add_user_point_form = formset_factory(AdditionalUserForm, extra=2) context = {'addition_user_form': add_user_point_form()} response = render(request, 'index.html', context) # if this is a POST request we need to process the form data if request.method == 'POST': add_user_form = add_user_point_form(request.POST) -
How to run a python script from clicking a button on a HTML webpage?
I currently have a python script that updates certain CSV files when ran (it web scrapes and updates the information of a CSV file). In my HTML page (index.html), I have a script tag inside index.html that reads the CSV file and displays it as a table on the webpage. However, what I now need to do is update the CSV file by pressing an HTML button on the webpage. This will update the CSV file so when I run the button to run the JS script, it will have updated values from the file. I searched and found it very hard to understand what they meant by using flask and Django (I don't know anything about setting up servers). I don't want to set up a Django webpage because I want to work with my current pure HTML webpage I wrote. I would appreciate it if the answer is up to date with the current standard solutions for running python scripts in HTML. Please ask if you need more information. Thanks. -
Django models Foreign key select_related
class A(models.Model): field = models.CharField(max_length=200) class B(models.Model): field = models.CharField(max_length=200) a = models.ForeignKey(A, related_name='my_set', on_delete=models.CASCADE) I wanna get "B" models from A queryset: Such as: qs = A.objects.all().select_related('my_sets') -
django updateview not showing existing data to form
update is working but template form is not showing existing data. django updateview not showing existing data to form. when update page is showing only existing file is showing but object data is not showing. updateview cannot send existing data to form view.py from django.shortcuts import render, redirect from django.core.files.storage import FileSystemStorage from .forms import BookForm from .models import Book from django.views.generic import TemplateView, ListView, CreateView, UpdateView from django.urls import reverse_lazy class BookUpdate(UpdateView): model = Book form_class = BookForm success_url = reverse_lazy('class_book_list') template_name = 'updatebook.html' model.py from django.db import models from django.urls import reverse # Create your models here. class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=100) pdf = models.FileField(upload_to='books/pdfs/') cover = models.ImageField(upload_to='books/covers/', null=True, blank=True) def __str__(self): return self.title forms.py from django import forms from .models import Book class BookForm(forms.ModelForm): class Meta: model = Book fields = ('title', 'author', 'pdf', 'cover') urls.py from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls.static import static from . import views urlpatterns = [ path('books/', views.book_list, name='book_list'), path('books/upload/', views.upload_book, name='upload_book'), path('books/<int:pk>/',views.delete_book, name='delete_book'), path('class/books/',views.BookListView.as_view(), name='class_book_list'), path('class/books/upload/',views.UploadBookView.as_view(), name='class_upload_book'), path('class/books/update/<int:pk>/',views.BookUpdate.as_view(), name='class_update_book'),''' updatebook.html {% load crispy_forms_tags %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h2> Upload Book to Database</h2> <form … -
How to get data out of a Django Model and in to the HTML Template?
I'm new to Django (and french so sorry if I'm not writing well) and I'm trying to display informations from my model Administrateur into my HTML Templates login.html but nothing is happening. This my Model class Administrateur(models.Model): nom = models.CharField(max_length=30) prenom = models.CharField(max_length=30) mdp = models.CharField(max_length=30) mail = models.CharField(max_length=30) def _str_(self): return self.name This is my view def Pseudo(request): administrateurs = Administrateur.objects.all() context={'administrateurs':administrateurs} return render(request, "login.html",context) This is my HTML {% load static %} {% block content %} {% for n in administrateurs %} {{ n.nom }} {{ n.prenom }} {% endfor %} {% endblock %} I'm not sure what to do with urls.py Thank you for help ! -
Remember users chosen theme
I'm making a toggle button for the user to choose between light and dark theme. I want Django to remember what them the user chose when they come back to the website. What would be the best approach to do this? Should I have an attribute for the user? Perhaps should I use a cookie? -
Django Extract Vimeo and Youtube Duration From The API
I have the following code that I am using to embed both Youtube and Vimeo videos into my django site. <div style="padding:56.25% 0 0 0;position:relative;"> <iframe src="{{ object.video_url }}?dnt=1&autoplay=0&title=0&byline=0&portrait=0" style="position:absolute;top:0;left:0;width:100%;height:100%;" frameborder="0" allow="encrypted-media; fullscreen" allowfullscreen></iframe> </div> <script src="https://player.vimeo.com/api/player.js"></script> Where {{ object.video_url }} can be either the following examples: https://player.vimeo.com/video/336812660 https://www.youtube-nocookie.com/embed/YE7VzlLtp-4 How would you be able to extract the {{ object.video_url }} duration which can either be from a Youtube or Vimeo video from the Youtube and Vimeo APIs? -
How to change admin list filter boolean field labels from yes/no to something else?
# models.py class BoolTest(models.Model): NO = False YES = True YES_NO_CHOICES = ( (NO, 'not completed'), (YES, 'completed') ) completed = models.BooleanField( default=NO, choices=YES_NO_CHOICES ) # admin.py class BoolTestAdmin(admin.ModelAdmin): list_filter = ('completed',) I want list filter labels to be 'not completed' and 'completed' instead of default 'yes'/'no'. How can I do this without defining custom ListFilter? Usage of choices from "fixed" ticket (as in exaple above) didn't work. Or I just missunderstand that issue. -
Django Import error....How do I get dj_database_url?
I'm currently trying to make a dating app, my first project from scratch. I downloaded a sample project to use as a reference and I want to fire it up on my local server and see what the actual website looks like so I can play around with it and understand the code better. However, after deleting the current database, and then trying to make a new one on my pc, I get ImportError: No module named dj_database_url I'm not sure what this is, as I'm still new to django/coding. I tried pip installing dj_database and looked over a couple things, but I still can't figure out what this is. And it's stopping me from being able to view the project site. here is the settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'u)-vf#0bv3!3)g-58(pox4_^-o$m8#5%idk3bmegowsimy%6)l' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*', 'localhost'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'registration', 'app', 'storages', ] … -
How to create mathematics operations with decimal in Django - [<class 'decimal.InvalidOperation'>]
A very simple save method causes this error : class Shift(models.Model): branch = models.ForeignKey(Branch, on_delete=models.CASCADE) employee = models.ForeignKey(Employee, on_delete=models.CASCADE) start_time = models.DateTimeField(auto_now_add=True) end_time = models.DateTimeField(null=True) closing_type_amount = models.DecimalField(max_digits=4, decimal_places=2, default=0) closing_actual_amount = models.DecimalField(max_digits=4, decimal_places=2, default=0) diff = models.DecimalField(max_digits=4, decimal_places=2, null=True) on_duty = models.BooleanField(default=True) def save(self, *args, **kwargs): self.diff = float(self.closing_type_amount) - float(self.closing_actual_amount) super(Shift, self).save(*args, **kwargs) The cause of this error is the line self.diff = float(self.closing_type_amount) - float(self.closing_actual_amount) NOTE when give inputs more than 100 it fails ,, when a small numbers like 5, 4 , 6, 11 it works normally . -
Django allauth with OpenID
I have, for the most part, got django-allauth running in a demo app. I am struggling a little with the final component, which is integrating OpenID logins. I have managed to successfully integrate an OpenID log-in via Steam. However, I would like to give the user a choice of a list of OpenID servers to use, and so far cannot figure it out. The django-allauth documentation gives this as an example of a config in settings.py: 'openid': {'SERVERS': [ dict(id='yahoo', name='Yahoo', openid_url='http://me.yahoo.com'), dict(id='hyves', name='Hyves', openid_url='http://hyves.nl'), dict(id='google', name='Google', openid_url='https://www.google.com/accounts/o8/id')] },… How do I access these servers/settings in a template, for example in a <select>? Also, the Google URL gives a 404, what is the correct Google OpenID URL? Sorry if these are simple questions, django noob. Thanks. -
How to add copy button wherever code tags appear in django
I have used django-pagedown package to create markdown editor. After adding content using markdown editor. while getting data from models, I want to add a copy button to the right corner or inside to the code tags just like StackOverflow to copy the code after clicking the copy button. class QuestionForm(forms.ModelForm): question_body = forms.CharField(widget=PagedownWidget()) class Meta: """Meta definition for Questionform.""" model = models.Question fields = ("question_title", "question_body") <div class="p-2 flex-grow-1" id="anSWER{{ forloop.counter }}"> <p>{{ answer.answer_text|markdown }}</p> </div> <div class="p-2 ml-auto"> <button">Copytext</button> </div> -
if and else statement in django
I have a search function where user search for state and on submit it takes them to a new page where i want to show them some specific info related to the state they searched about. i am trying to use if and else statement but it doesn't worked, may be because am new to django and python... Here is what i tried: {% extends 'base.html' %} {% block content %} <h2 style="text-align: center;">{{ state | title }}</h2> {% if State == California %} <h1>Show this</h1> {% else %} <h1>Show this to all others.</h1> {% endif %} {% endblock content %} my view.py import requests from django.shortcuts import render from . import models def home(request): return render(request, 'base.html') def chose_state(request): state = request.POST.get('state') models.State.objects.create(state=state) stuff_for_frontend = { 'state': state, } return render(request, 'myapp/chose_state.html', stuff_for_frontend) -
Django Form Search Filter
I am fairly new to django forms, i tired looking up how to tackle this issue, but im having a hard time trying to find a solution. What I would like to do is use that search bar to search for the form right underneath it to filter out items. For example, if i type "apple" it would only give me the items with the word "apple" but only for that specific scroll able list. The overall function of this is you can scroll down a list of menu items and drag it from the right side to the left side in order to "build a menu". But the search function will make it easier to locate item, rather than scroll and look for it, because there are many duplicates (Apples: cut; Apples: whole; etc) Here is a picture of the html Here is the code: <div class="row"> {{ mealItemForm.management_form }} {% for formMeal in mealItemForm %} <div class="form-group col-md-9"> {{ formMeal.mdi }} {{ formMeal.mealType }}<br> <form type="GET"> <input type="search" style="margin-left:65%; margin-bottom:5px;"> <button class="btn btn-primary" style="margin-left:5px;">search</button> </form> <br/>{{ formMeal.foodItem}}<br/> </div> {% endfor %} </div> -
Where is the User model stored in django?
User is a model in django.contrib.auth.models. I am currently developing a user registration and login system using in-built django authentication system. I am using PostgreSQL as the underlying database instead of sqlite. The migrations were successful to the point where corresponding tables were generated in my postgres database. I am assuming that the table auth_user stores all the details of the registered user. To test my database setup and authentication system, I am registering with a random user and check the auth_user table. In the table, I could find the username details for which I registered. Next, I clear the contents of the auth_user table to start afresh. But now when I register with the same username, I get the message A user with this username already exists. under the username field in my form. How is this possible? I cleared the contents of auth_user table in my Postgres database. Then I create a separate view to display the contents of User model which belongs to django.contrib.auth.models and find that the username I registered earlier is being displayed even though the auth_user table is currently empty. I am really curious about this. Am I missing something? Please clarify. I humbly … -
How can i count the user hit the api using token?
I created some API's. it will provide some data. but here i want know how many times used my api with registered user in Django and DRF. I used django adn djangorestframework. and for token rest_framework.authtoken. suggest me any idea to count the user request to access the my api with generated token. can i count the user request how many times it will used my token.