Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Django printing email instead send. I'm already using smtp backend
I'm using "django-rest-auth" to reset the password. But when I enter the email to reset the password, instead of sending the email, django displays the rendered html in the terminal. settings.py REST_AUTH_SERIALIZERS = { "PASSWORD_RESET_SERIALIZER": "emails.serializers.PasswordResetSerializer", } EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.mailgun.org" EMAIL_PORT = 587 EMAIL_HOST_USER = "postmaster@mydomain.com" EMAIL_HOST_PASSWORD = "my_secret" EMAIL_USE_TLS = True emails/serializers.py from django.contrib.auth.forms import PasswordResetForm from django.contrib.auth import get_user_model from django.conf import settings from rest_framework import serializers User = get_user_model() class PasswordResetSerializer(serializers.Serializer): email = serializers.EmailField() password_reset_form_class = PasswordResetForm def validate_email(self, value): self.reset_form = self.password_reset_form_class(data=self.initial_data) if not self.reset_form.is_valid(): raise serializers.ValidationError("Erro: dados inválidos") if not User.objects.filter(email=value).exists(): raise serializers.ValidationError("Endereço de email invalido") return value def save(self): request = self.context.get("request") opts = { "use_https": request.is_secure(), "from_email": "No Reply - Geeknoon <no-reply@geeknoon.com>", "subject_template_name": "emails/subject_template.txt", "email_template_name": "emails/reset_password.html", "request": request, } self.reset_form.save(**opts) Example of terminal output: https://imgur.com/a/w9pi78d -
Rendering a Django application with static pages
I have a Django web application, I want to show the application to clients with sending them multiple static pages (i.e. multiple HTML files and JS or CSS folders). I found django-distill package here but I am not sure should I add it to the installed applications of my project or are there other strait-forward alternatives. -
Convert javascripts' null to Django None when doing request
I am sending the following request to Django server: GET '/api/project/R0009_il/saved_variants/?categoryFilter=null' And in Django code: category_filter = request.GET['categoryFilter'] I expect the following check to fail but it does not: if category_filter: print(category_filter) Instead it prints null, so javascripts' null is True which is obviously wrong. How to fix that? I found the solution to the reverse task, but not to the current one: Convert Python None to JavaScript null -
How to add a button to update another model in Django UpdateView
I have ListView that shows list of Person Models for a Home Moldel. When I click on a respective link for a Person, an UpdateView is called for the Person. I can click a "Cancel" or "Update" button once I am view for the Person. When I click either buttons, I am brought back to the ListView of the Persons. Now, I want to add another button "Update Another". This button should bring the next Person in the ListView that should be updated. See, example below: ListView --Template (Project) Person1 <link1> Person2 <link2> Person3 <link3> Person4 <link4> UpdateView --Template (Person1) forms fields.... [Cancel] [Update] [Update Another] If a user clicks on "Update Another", the user should be seeing the UpdateView --Template for Person2 and so... It could be cyclic. -
'WSGIRequest' object has no attribute 'CustomUser'
I want to create a patient system. User can add patients but I want to users can see only their patients. I used patient_list = newPatients.objects.filter(current_user.id) `but I get an error. How can I fixed it? settings.py 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', ] views.py @login_required def patient_list(request): current_user = request.CustomUser patient_list = newPatients.objects.filter(current_user.id) query = request.GET.get('q') if query: patient_list = patient_list.filter( Q(first_name__icontains = query) | Q(last_name__icontains = query) | Q(dept__icontains = query) | Q(address__icontains = query) | Q(phone__icontains = query) | Q(notes__icontains = query)) paginator = Paginator(patient_list, 5) # Show 5 contacts per page page = request.GET.get('page') try: patients = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. patients = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. patients = paginator.page(paginator.num_pages) return render(request, "patients.html", {'patients':patients}) Traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/patients/ Django Version: 3.0.3 Python Version: 3.7.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', 'patients', 'widget_tweaks', 'crispy_forms', 'ckeditor'] Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware') Traceback (most recent call last): File "C:\Users\edeni\senior\myenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\edeni\senior\myenv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response … -
How to always listen for amazon sqs in python django rest framework
I am new to python django rest framework and I need to listen amazon sqs continuously in framwwork. where I can run while loop infinitely or Can I use Celery[sqs] for this purpose? Thanks in advance. -
How to fix "the `.create()` method does not support writable nested fields by default" in Django API
I have a problem with creating new ratings for cars. When i try to send a post request from Postman in order to create/add a new rating for a specific car i get the error: The `.create()` method does not support writable nested fields by default. These are my models: class Car(models.Model): name = models.CharField(max_length=50) symbol = models.CharField(max_length = 5) def __str__(self): return self.name class Type(models.Model): name = models.CharField(max_length = 50) fuel = models.CharField(max_length = 1)##1 or 2 for fuel type car = models.ManyToManyField(Car) def __str__(self): return self.name class Rating(models.Model): rating = models.IntegerField(validators=[ MaxValueValidator(10), MinValueValidator(0) ]) car = models.ForeignKey(Car, on_delete=models.CASCADE) type = models.ForeignKey(Type, on_delete=models.CASCADE) def __int__(self): return self.rating My serializers: class CarSerializer(serializers.ModelSerializer): class Meta: model = Car fields = ('id','name') class TypeSerializer(serializers.ModelSerializer): car = CarSerializer(many=True) class Meta: model = Type fields = ('id','name', 'fuel', 'car') #depth=2 class RatingSerializer(serializers.ModelSerializer): module = ModuleSerializer() class Meta: model = Rating fields = ('id','rating', 'car', 'type') When i try to do a post request to rating such as : {"rating":5, "car": 2,"type":{"id":1,"name":"OffRoad","fuel":"1","car":[{"id":2,"name":"Ford"}] } } I get: The `.create()` method does not support writable nested fields by default. -
How do I write a custom tag in my `views.py` and call it in my template
This is the method I want to call. def is_liked(post, user): *post is a single instance of a post model* *user is the current logged in user* return post.likes.filter(username = user).exists() I've tried register = template.Library() @register.simple_tag def is_liked(post, user): *rest of method* and called it with {% if is_liked post user %} *Something* {% else %} *Something else* {% endif %} and I get the error Unused 'post' at end of if expression. -
Are making relationships between tables like this is correct? Are there better ways to make relationships between tables than this way?
[ enter image description here ]1 CREATE TABLE Users ( user_id integer ); CREATE TABLE Schools ( schoole_id integer PRIMARY KEY AUTOINCREMENT, address_id integer ); CREATE TABLE ِِAcademic_year ( year_id integer ); CREATE TABLE Employees ( employee_id integer PRIMARY KEY AUTOINCREMENT, user_id integer, address_id integer ); CREATE TABLE Addresses ( address_id integer PRIMARY KEY AUTOINCREMENT ); CREATE TABLE Students ( student_id integer PRIMARY KEY AUTOINCREMENT, user_id integer PRIMARY KEY AUTOINCREMENT, address_id integer PRIMARY KEY AUTOINCREMENT ); CREATE TABLE Center ( center_id integer PRIMARY KEY AUTOINCREMENT, student_id binary, school_id integer PRIMARY KEY AUTOINCREMENT, year_id integer PRIMARY KEY AUTOINCREMENT, mark_id integer, classroom_id integer, level_idclassroom_id integer, material_id integer, user_id integer, employee_id integer, degree integer, grade text ); CREATE TABLE Marks ( mark_id integer PRIMARY KEY AUTOINCREMENT ); CREATE TABLE Classroom ( classroom_id integer PRIMARY KEY AUTOINCREMENT ); CREATE TABLE Levels ( level_id integer ); CREATE TABLE Material ( material_id integer PRIMARY KEY AUTOINCREMENT ); Each of the tables is related to many to many relationships across the center table I use Django What is best, making one table that links all the tables that have a lot to many relationship, or making a table specific to each relationship many to many. Noting the … -
Django dropdown showing model Fields
I want to display a dropdown that contains the string values of the Field names in one of my models. models.py : class MyModel(models.Model): meat = models.CharField() veggies = models.CharField() fish = models.CharField() forms.py: class MyModelForm(ModelForm): class Meta: model = MyModel fields = ['foodTypes'] The dropdown should then show meat veggies fish -
Django get_or_create ValueError
Trying to add rows from a DataFrame into Django model. models.py: class CreditIndex_TEST(models.Model): loanBook = models.ForeignKey(LoanBooks, on_delete=models.CASCADE) run_date = models.DateField() index_date = models.DateField() index_CD = models.IntegerField() Index_value = models.FloatField() class Meta: constraints = [ models.UniqueConstraint(fields= ['loanBook','run_date','index_date','index_CD'], name='unique_CreditIndexPair') ] views.py: for index, row in tempDf.iterrows(): obj, created = CreditIndex_TEST.objects.get_or_create( loanBook=dbname, run_date= run_date, index_date=row['Date'], index_CD=1, Index_value=row['CreditIndex_CD1'] ) ERROR:: ValueError: Field 'id' expected a number but got 'Botswana_TU'. I don't understand why I am being asked to specify id. The record I am trying to add to the model does not exist and therefore Django should create it and assign id, not expect it from me? -
AssertionError: Expected a `date`, but got a `datetime`. Refusing to coerce, as this may mean losing timezone information
I am facing some issues while creating an API Here is my model class Education(AuditFields): user = models.ForeignKey(User, on_delete=models.CASCADE) school = models.CharField(max_length=255, blank=True) field_of_study = models.CharField(max_length=255, blank=True) start_year = models.DateField(default=datetime.now) end_year = models.DateField(default=datetime.now) This is my serializer : class EducationSerializer(ModelSerializer): class Meta: model = Education fields = '__all__' views : class EducationCreateView(CreateAPIView): def get_queryset(self, *args, **kwargs): queryset_list = Education.objects.filter( user=self.request.user) return queryset_list serializer_class = EducationSerializer def perform_create(self, serializer): serializer.save(user=self.request.user) If I am post something it shows the following message { "user": [ "This field is required." ] } if I change my serializer like this class EducationSerializer(ModelSerializer): class Meta: model = Education fields = '__all__' extra_kwargs = {'user': {'required': False}} I am getting an error like this Expected a date, but got a datetime. Refusing to coerce, as this may mean losing timezone information. Use a custom read-only field and deal with timezone issues explicitly. How to resolve this . -
Django Forms with dynamic field values
First time using Django Forms. I'm stuck trying to get the dropdown choices to reload. My forms.py is below. When the database state changes, the choices do not. I suppose that this is because they are defined at a class level, which means the query happens at initialisation of the module? I've found that the only way to get my dropdowns to update is to restart the webserver. How can I have the database queries evaluate on every request? forms.py from django import forms from app.models import Collection, ErrorMessage, Service class FailureForm(forms.Form): collections = [(collection.value,)*2 for collection in Collection.objects.all()] error_messages = [(message.value,)*2 for message in ErrorMessage.objects.all()] services = [(service.value,)*2 for service in Service.objects.all()] collection = forms.CharField(label='collection', max_length=100, widget=forms.Select(choices=collections)) error_message = forms.CharField(label='error_message', max_length=400, widget=forms.Select(choices=error_messages)) service = forms.CharField(label='service', max_length=100, widget=forms.Select(choices=services)) -
DJango - NoReverseMatch Error - What is wrong?
I am trying to set up a user password change from built on this tutorial. Unfortunately, on success, this tutorial just returns the user to the change password form, which doesn't seem very satisfactory. So, I am attempting to redirect the user user to a success template. My code is in an app called your_harmony base.py INSTALLED_APPS = [ ... 'your_harmony', ... ] urls.py urlpatterns = [ ... url(r'^your-harmony/', include('your_harmony.urls')), ... ] your_harmony/urls.py urlpatterns = [ url(r'password/$', change_password, name='change_password'), url(r'password_changed/$', password_changed, name='password_changed'), ] views.py def change_password(request): if request.method == 'POST': form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) # Important! messages.success(request, 'Your password was successfully updated!') return redirect('password_changed') else: messages.error(request, 'Please correct the error below.') else: form = PasswordChangeForm(request.user) url = 'registration/change_password.html' return render(request, url, {'form': form}) def password_changed(request): url = 'password_changed.html' return render(request, url, {}) When I use the form to change the password and submit, the password is changed correctly, but I get the error NoReverseMatch at /your-harmony/password_changed/ However, when I hover over the link to call the change password form, the url displayed in the browser is 127.0.0.1:8000/your-harmony/password Can someone please point what I am doing wrong? -
Django test error in command line: <model name> matching query does not exist
This is my tests.py file: from django.test import TestCase from .models import * from django.contrib.auth.models import User class ArticleTestCase(TestCase): @classmethod def setup(self): Article.objects.create( article_title="title1", article_content="content of article", ) def test_article_title(self): a1 = Article.objects.get(pk=1) article_name = a1.article_title self.assertEquals(article_name, 'title1') But, i'm always getting this error: Traceback (most recent call last): File "F:\Django_Blog_Live\swagato_blog_site\blog_api\tests.py", line 16, in test_article_title a1 = Article.objects.get(pk=1) File "F:\Django_Blog_Live\env\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "F:\Django_Blog_Live\env\lib\site-packages\django\db\models\query.py", line 415, in get raise self.model.DoesNotExist( blog_api.models.Article.DoesNotExist: Article matching query does not exist. And the error description is pointing at this statement: a1 = Article.objects.get(pk=1) -
How do you apply the styling of text fetched from the database in Django?
I'm creating a blog. In the post page, I am fetching the text from the database, but the styling is not being applied. Instead, I am getting the "raw" output. I am using {{post.text}} to fetch the post content and I am getting: <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus eget leo cursus, tempus leo non, sodales sem.</p> Instead of the text with the <p> styling. I am using django-ckeditor.