Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError at / 'str' object has no attribute 'get' in Danjo
Exception Value:'str' object has no attribute 'get' Exception Location: C:\Python\Python38-32\Scripts\myenv\lib\site-packages\django\forms\models.py, line 346, in _get_validation_exclusions models.py from django.db import models class HomePageModel(models.Model): first_name = models.CharField(max_length = 20) last_name = models.CharField(max_length = 20) password = models.CharField(max_length = 12) confirm_password = models.CharField(max_length = 12) phone_number = models.CharField(max_length = 10) gender = models.CharField(max_length = 6) city = models.CharField(max_length = 20) def __str__(self): return self.first_name forms.py from django import forms from .models import HomePageModel from django.core.exceptions import ValidationError import re class HomePageForm(forms.ModelForm): class Meta: model = HomePageModel fields = "__all__" def clean(self): super(HomePageForm, self).clean() first_name = self.cleaned_data.get('first_name') try: regex = re.compile('[@_!#$%^&*()<>?/\|}{~:]') flag_decimal = 0 flag_alpha = 0 if len(first_name) > 20: raise ValidationError('Fisrt Name can not be more than 20 characters') if (regex.search(first_name) != None): raise ValidationError('Fisrt Name can not have a special character') else: for char in first_name: if char.isdecimal(): flag_decimal = 1 if char.isalpha(): flag_alpha = 1 if flag_decimal == 1 or flag_alpha == 0: raise ValidationError('Fisrt Name can not have a number') return first_name except ValidationError as e: print(e) .... #rest validation views.py from django.shortcuts import render from django.http import HttpResponse from .forms import HomePageForm def home_page(request): if request.method == 'POST': form = HomePageForm(request.POST) if form.is_valid(): form.save() return HttpResponse('Successful') else: return render(request, … -
django.db.utils.DataError: invalid input syntax for type json, (Token "add" is invalid., JSON data, line 1: add...)
I'm using django as my backend and it was working very fine, but after I tried to rplace text = models.JSONField(blank=True, null=True) with text = models.TextField(blank=True, null=True)and also after a ranpython manage.py migrate` I got this err: return self.cursor.execute(sql, params) django.db.utils.DataError: invalid input syntax for type json DETAIL: Token "add" is invalid. CONTEXT: JSON data, line 1: add... models.py class elements(models.Model): tag = models.CharField(blank=True, null=True, max_length=20) // it was text = models.TextField(blank=True, null=True) // now it is text = models.JSONField(blank=True, null=True) src = models.TextField(blank=True, null=True) # problem: styles replace spaces with slashes (/) # I tried: json field but did'nt work. style = models.JSONField(blank=True, null=True) main = models.ForeignKey( 'self', null=True, blank=True, related_name="sub", on_delete=models.PROTECT) def __str__(self): return "<elements: {} {}>".format(self.tag, self.text, self.src, self.style) def __repr__(self): return self.__str__() note: when I run python manage.py runserver every thing work just fine but it says You have 3 unapplied migration(s). -
Django dynamic card redactor / processor showing on landing page
My goal is to have my website’s home page appear like this where only the form block element is present (marked by the large red “A”). After the website visitor enters their card number on that landing page, Django should redact it and render the same home page but the form should be gone and only the field divider with the processed output showing (marked by the large red “B”) as it appears in this pic on imgur. How do I achieve this? These two pics are kind of like a ‘mock up’, meaning I just commented out the form and divider sections. When only A shows when B is commented out, I lose the functionality. For the functionality to work, ‘A’ and ‘B’ shows at the same time as shown here, which is not what I want. I need to modify the template (perhaps by adding conditional logic?). I’m not sure how to tell Django to serve the template so that only ‘A’ shows first and then, after the site visitor enters their 12 digit card number, remove ‘A’ and only show ‘B’. Here is the template that I am working with showing the card processor form/divider elements: <div … -
ValidationError not display for MultiSelectField in Django
According to Django's doc, we can raise the ValidationError inside Form class using clean_<Fieldname> function. In my model I have a field called teacher_department which is a MultiSelectField from third party (django-multiselectfield). I gave blank=True to that field for some reasons. Now I want to check the field if user fill it or not and if not then raise an error. Before I checked it by doing a condition inside views.py and gave the error message but now I want to do it inside Form class by raising the ValidationError. Other fields such as email or password or first_name works just fine except teacher_department field. here is my models.py class CustomUser(AbstractUser): email = models.EmailField(_('Email Address'), unique=True) teacher_department = MultiSelectField(choices=department_choice, blank=True) forms.py and how I raise the ValidationError class TeacherRegisterForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = ['email', 'teacher_department', ...] def __init__(self, *args, **kwargs): super(TeacherRegisterForm, self).__init__(*args, **kwargs) self.fields['email'].widget.attrs.update(email_attr) def clean_email(self): email = self.cleaned_data.get('email') email_check = CustomUser.objects.filter(email=email).exists() if email_check: raise forms.ValidationError(_('Email is already taken!'), code='invalid') def clean_teacher_department(self): teacher_department = self.cleaned_data.get('teacher_department') if teacher_department is None: raise forms.ValidationError(_("Department required"), code='invalid' template <form method="POST" id="#teacher_register_form"> {% csrf_token %} <div class="md-form pt-2"> <label>Email Address</label> {{ form.email }} <small style="color: red;">*{{ form.email.errors|striptags }}</small> </div> <div class="row mt-3"> … -
Unable to migrate with django and sqlite (django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table)
I'm filling a SQLite Database and want to use it in my django project. Previously that worked fine but now when I want to migrate I get the following error: Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Traceback (most recent call last): File "C:\Daten\Software\venv_SQLdatabase\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Daten\Software\venv_SQLdatabase\lib\site-packages\django\db\backends\sqlite3\base.py", line 383, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such column: None The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Daten\Software\venv_SQLdatabase\lib\site-packages\django\db\migrations\recorder.py", line 67, in ensure_schema editor.create_model(self.Migration) File "C:\Daten\Software\venv_SQLdatabase\lib\site-packages\django\db\backends\sqlite3\schema.py", line 34, in __exit__ self.connection.check_constraints() File "C:\Daten\Software\venv_SQLdatabase\lib\site-packages\django\db\backends\sqlite3\base.py", line 311, in check_constraints (rowid,), File "C:\Daten\Software\venv_SQLdatabase\lib\site-packages\django\db\backends\utils.py", line 99, in execute return super().execute(sql, params) File "C:\Daten\Software\venv_SQLdatabase\lib\site-packages\django\db\backends\utils.py", line 67, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Daten\Software\venv_SQLdatabase\lib\site-packages\django\db\backends\utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Daten\Software\venv_SQLdatabase\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Daten\Software\venv_SQLdatabase\lib\site-packages\django\db\utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Daten\Software\venv_SQLdatabase\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Daten\Software\venv_SQLdatabase\lib\site-packages\django\db\backends\sqlite3\base.py", line 383, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such column: None During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 21, … -
Django read tsv and save data to db
I am a beginner to django and i am facing an issue in reading data . Example my file contains 400 rows which needs to be saved in the database . when i run the functionality locally i am able to add the data to db , but when i push the same functionality to heroku . i am not able to add the data to db , i keep getting an error . Thanks in Advance for your suggestions . -
Get Data from Inline with Admin.User Model
I am trying to use an 'augmentation' table with the Admin.User Model to store additional data related to that user/login. Here is my admin.py class UserProfileInline(admin.StackedInline): model = AppUserProfile can_delete = False verbose_name_plural = 'profile' # Define a new User admin class UserAdmin(BaseUserAdmin): inlines = (UserProfileInline,) # Re-register UserAdmin admin.site.unregister(User) admin.site.register(User, UserAdmin) Here is my models.py class AppUserProfile(models.Model): user = models.ForeignKey(User, on_delete=models.DO_NOTHING) usr_tpid = models.CharField(max_length=20) usr_cstid = models.CharField(max_length=20) db_table = 'app_user_profile' Here is my views.py where I'm trying to get the usr_cstid from the login value. def login_view(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): print(request.POST) username = form.cleaned_data['userName'] password = form.cleaned_data['password'] userInfo = AppUserProfile.objects.all().filter(user=username) However I'm getting the following error: ValueError: invalid literal for int() with base 10: 'supplier_ad' I am not sure what I have wrong, or how to link back to those values. -
Django FormView manually set session data lost after redirect
I am using FormView to get some input from the user. I then try to set some of that data into the session to be used after the form validates and the user is redirected. The data is however lost. The view: class SomeFormView(FormView): template_name = 'something.html' form_class = SomeForm def form_valid(self, form): self.request.session['some_key'] = 'some value' # According to manual, this should work self.request.session.modified = True # Hail Mary self.request.session.save() return super().form_valid(form) If I look at the self.request.session contents prior to the redirect, it will have the value I've set as: '_session_cache': {'some_key': 'some_value'} But when I arrive at the redirect, the data is nowhere to be found. I tested this on Django 3.1.1 and Django 2.2.16, with both acting the same -
Block invalid HTTP_HOST headers in Apache in AWS ElasticBeanstalk
I have several websites running Django/Apache in AWS ElasticBeanstalk. My only problem is the hundreds of emails I receive every day with this subject: [Django] ERROR (EXTERNAL IP): Invalid HTTP_HOST header: WHATEVER. You may need to add WHATEVER to ALLOWED_HOSTS. That's because I have properly configured the ALLOWED_HOSTS variable in my Django configuration, but I need Apache to block all invalid HTTP_HOST headers so they don't even reach Django and get rid of these hundreds of emails every day. There are dozens of examples of how to do that in Apache here and there, I know, but I haven't found a single example of how to do it when deploying in AWS ElasticBeanstalk. The main difference when deploying there is that I can't add a configuration that only works within a <VirtualHost> block. I need something that works properly outside of a <VirtualHost> block, allowing me to put it in a standalone Apache config file. Here there is a really nice explanation of all this: https://stackoverflow.com/a/38751648/1062587, however, that question was asking about RewriteRules and not blocking invalid hosts. What I would need is the proper configuration for a file similar to this one: files: "/etc/httpd/conf.d/require_valid_hosts.conf": mode: "000644" owner: root group: … -
Django url parameters confusion
Hi: I have the hope you can helpme with my "django existential doubt". Every time Im ask google for this the same thing happens to me (english is not my mother tongue), I have this doubt, this confusion: Whats is the name of this things??? "my/happy/int:year/" this is called "url parameter" but "my/happy/year?y=2020" also is called "url paramenter" or not?? Thank you for your ilumination! -
My demo django project doesn't start server after a restarting command prompt
I have created demo django project, now I cant run the server. I'm getting "ImportError: Couldn't import Django" I dont know what I'm missing. -
How to use Angular Datatables with Django Backend
I'm trying to use Datables with Django but I couldn't figure out how to get data in the correct form. Django's rest API is returning an object but the Angular Datatables want a JSON file, so how can I achieve this result? Here's what I've tried: HTML: <table datatable class="row-border hover"> <thead> <tr class="header"> <th class="date">Id</th> <th class="date">Nom</th> <th class="societe">Email</th> <th class="evenements">Date d'inscription</th> <th class="facturePDF">Actif</th> </tr> </thead> <tbody *ngIf="persons?.length != 0"> <tr *ngFor="let item of Users;let index=index"> <td class="text-monospace pt-3 pl-4"> {{item?.id}} </td> <td class="text-monospace pt-3 pl-4"> {{item?.name}} {{item?.lastname}} </td> <td class="text-monospace pt-3 pl-4"> {{item?.email}} </td> <td class="text-monospace pt-3 pl-4"> {{item?.date_joined.slice(0,10)}} </td> <td class="text-monospace pt-3 pl-4"> {{item?.is_active}} </td> </tr> </tbody> <tbody *ngIf="Users?.length == 0"> <tr> <td colspan="3" class="no-data-available">No data!</td> </tr> <tbody> </table> admin.component.ts: ngOnInit() { this.dtOptions = { pagingType: 'full_numbers', pageLength: 2 }; this.GetUsers(); } GetUsers(){ this.ApiService.list_users(this.page).subscribe( data => { this.Users = this.Users.concat(data); }, error=>{ console.log(error); } ) } The "list_users" function call Django to retrieve data from the database: @api_view(['GET','POST','DELETE']) def list_annonces(request): if request.method == 'GET': annonces = Annonces.objects.all().order_by('-id') count = Annonces.objects.count() try: page = int(request.GET.get('page')) except Exception: page = 1 limit = count offset = (page-1) * 10 annonces_data = AnnonceSerialize(annonces.all()[offset:limit], many=True) return Response(annonces_data.data, status.HTTP_200_OK) ``` -
how to use LOGIN_REDIRECT_URL in that case
LOGIN_REDIRECT_URL doesn't work when setting URL with arguments. urls.py urlpatterns = [ path('user/<str:username>', views.UserTaskListView.as_view(),name='user-tasks') ] settings.py LOGIN_REDIRECT_URL='user-tasks' #<===== doesn't work error message enter image description here -
Autogenerate ID field in Django models combining multiple fields
I am trying to design a web-app for task management. In my Task model there is column Task ID other than AutoField ID. I was trying to populate this field in such a way that it reflects content of different fields. For eg: I have multiple organizations, multiple departments, so what I am trying to achieve is to generate a Task ID which reflects Organization, Department and sequence number like TSK(01)(02)01 where (01) represents a particular organization (02) represents department and rest is an auto incrementing serial number. So any ideas?? -
Django filtering on related models attributes
class Count(models.Model): start_time = models.DateTimeField(null = True, blank = True) end_time = models.DateTimeField(null = True, blank = True) class AccessRecord(models.Model): user = models.ForeignKey(get_user_model(), related_name = 'accesses', on_delete = models.CASCADE) count = models.ForeignKey(Count, related_name = 'accesses', on_delete = models.CASCADE) With this model scheme, how can i filter on a Count queryset based on the user? For example, i want every count object that has the first Access Record with a certain user id. user_id = 2 all_counts = Count.objects.all() list(filter(lambda x: x.accesses.first().user.pk == user_id, all_counts)) ^^ This would work. However i get a list instead of a query set (i still need to order_by, etc..) What's the best alternative here? -
Responsive design combined with Bootstrap and Django doesn't work
I do not know where I make errors. What is not correct in my code? I have website with subpages as below. Responsive design doesn't works. Is it related to any mistake in HTML/CSS code or instead of media queries I should use any specific way of making responsive design in bootstrap? Generally there is a problem with rows and columns - I can't change margins and font size responsively. Might it be related to django inheritance mechanism? {% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeN$ <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3$ <link rel="stylesheet" type="text/css" href=relax/css/grid.css"> <title>Visyrelax</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> body { background: #F8F8FF; } /* Adding !important forces the browser to overwrite the default style applied by Bootstrap */ .row{ margin:100px; } @media (min-width: 576px) { @include media-breakpoint-up(sm) .row{ font-size:10px; margin:10px; } } @media (min-width: 768px){ @include media-breakpoint-up(sm) .row{ font-size:20px; margin:10%; } } @media (min-width: 1200px){ @include media-breakpoint-up(sm) .row{font-size:60px;} p{ font-size:25px; } } </style> </head> <body> <nav class="navbar navbar-dark bg-dark"> <a class="navbar-brand" href ="{% url 'index'%}"> <p style="font-size:40px;"> &nbsp;&nbsp; <font color=DodgerBlue> Visy</font><font color$ <div class="navbar"> <a class= "nav-item nav-link" href ="{% url ‘a’%}”><font color=white>a</font></a> <a class= "nav-item nav-link" href ="{% url ‘b’%}”><font color=white>b</font></a> <a class= "nav-item … -
A way to check coverage of API tests for Django applications with Pytest
I have an application based on Django framework. Under the repo of the Django app, there is a repo which contains API tests based on Pytest framework. I am using requests library to send a request to the server, and asserting on the response data. An example of API test: import requests def test_some_api(self): s = requests.Session() response = s.get('/api/some_api') assert response.status_code == 200 Is there any way to know how many lines of code ran out of total amount of code lines of a given module? I managed to get a nice report with pytest-cov, but it works only for Unittests (calling functions directly from server repo). -
How to refresh 'refresh token' in django
Whenever I get a new access token using Refresh token, I want to get it reissued as well. So after coding as I thought, the refresh token was the same as the one issued before. How can I get a refresh token again? Here is my code. views.py class customRefreshView (GenericAPIView) : serializer_class = customTokenRefreshSerializer def post (self, request) : serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) try : token = RefreshToken(serializer.data['refresh']) except : return Response({'message': '잘못된 refresh token 입니다.'}, status=401) data = { 'token_type': 'Bearer', 'access_token': str(token.access_token), 'expired_at': str(datetime.now() + timedelta(minutes=30)), 'refresh_token': str(token), 'refresh_token_expires_at': str(datetime.now() + timedelta(hours=8)) } return Response(data, status=200) -
How to push data in selected data in django?
i Want to push key and data in to Selected data array .i am using mongodb database. i have two models in my lesson model class LessonsModel(models.Model): course_id = models.CharField(max_length=255) lesson_name = models.CharField(max_length=255) lesson_day = models.CharField(max_length=255) my course model class CourseModel(models.Model): course_name = models.CharField(max_length=255,blank=False) course_description = models.TextField(blank=False) course_image = models.ImageField(upload_to='course/',blank=False) i am selecting all data from my lessons model using following code. def fun(request): data=LessonsModel.objects.all() in my html file i am displaying this data. {% for newdatain data%} <tr> <td>lesson_name</td> <td>lesson_day </td> <td>course name(i want to display)</td> </tr> {% endfor %} now i want to display course name here.for that i need to select data from CourseModel. LessonsModel is having course_id. i want to append course_name into my 'data' object.how to to that? -
Django not serving HTML table in template (word counter web app)
Summary: Django is not rendering a basic 2 column by 11 row HTML table containing the top 10 most commonly used words in a large text file (Alice and Wonderland which is a public domain work). But right now the table is empty. Details: The table currently rendering on the web page looks like this, see here on imgur. In that pic, notice the bottom right corner, the table is empty. The fully populated word counter table and its contents rendering when a web user navigates to http://127.0.0.1:8000/counters. See here on imgur. However the problem there is that then the blog post lorem ipsum content is empty. See here: Here is my parent top level urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), # path('', include('mortems.urls')), path('', include('redactors.urls')), path('', include('posts.urls')), path('', include('counters.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Here is my counters app’s views.py: from django.shortcuts import render from collections import Counter import re from nltk.corpus import stopwords def counters(request, text=""): """ This function processes the top 10 most common words in a text file and then renders them. """ text = open("counters/Alice.txt", "r").read().lower() stoplist = stopwords.words('english') … -
Javascript how to know the current user? Session variable dont work? Uncaught (in promise) ReferenceError: require is not defined
SO this is my js code document.addEventListener('DOMContentLoaded', function() { document.querySelector('#inbox-view').innerHTML = `<p class="header" >Messages</p> `; fetch('/inbox') .then(response => response.json()) .then(messages => { messages.forEach(message => { let msection = document.createElement("div"); //create a clickable area let content = `<a href="#" class="posta"><img src="${message.senderimage}" class="rounded-circle"> <h4> ${message.sendername}</h4> <p style="display:inline;"> @${message.sender}</p> <p class="posta" id="myMessage"> ${message.content}</p> </a> <br> <br> <hr>`; msection.innerHTML = content; //set its content msection.setAttribute('class','msec'); //set its style msection.href ="#"; // make it clickable var session = require('express-session') if(`${message.sender}` != session){ document.querySelector('#inbox-view').append(msection); } What I want is I have this dynamic content in a Django Project. I want to display only the messages didn't send by the current user( basically display an inbox, not reply messages) In this section of my code var session = require('express-session') if(`${message.sender}` != session){ document.querySelector('#inbox-view').append(msection); } I want to check if the sender is current user if so I don't want to display that message. I already install thee package npm install express-session but still gives me this error: Uncaught (in promise) ReferenceError: require is not defined at inbox:130 (Without this session thing code works just fine) So what is the way of knowing the logged-in user? Is there any other way? Thank you -
File manager for amazon s3 in django admin (for django-ckeditor images)
Im looking for possibility to manage uploaded files to s3 bucket in django admin. Im sending some images to s3 via django-ckeditor. But ckeditor can only upload images, not delete. So after few month my bucket will be full of trash. I want add possibility to my django admin to manage that images. Maybe Ckeditor has some plugins for it? Or some django file managers? I found only that old question - How to remove images uploaded with django-ckeditor? -
Is there support for ordinal number suffixes localization?
For example if I have n-th apple (1st apple, 2nd apple, 3rd apple), how will this be translated in django? Is there some function to get suffix for given n? Looks like this depends on the gender of the word: 1re pomme, 2e pomme 1r homme 2e homme -
how to get list of active celery tasks inside django views
I want to get the list of all active celery tasks inside django views. When I looked online I found this link. I tried implementing this inside of django views like this from celery.app.control import Inspect def index(request): inspect = Inspect() print(inspect.active()) return render(request, 'index.html') but this give me the following error 'NoneType' object has no attribute 'control' Not sure what i am doing wrong -
Django Rest Framework - Serializing optional OneToOne relation
Suppose I have a Rating model used to store ratings on specific categories. Users can either provide a generic rating on a specific category, or they can provide a rating on a specific category guided by a question they were asked. The question thus is an optional field. Please note that this is a simplified example. In reality I am dealing with multiple optional fields. Therefore I would like to avoid using null for optional fields. To accomplish this I have created the following two models: class Rating(models.Model): score = models.IntegerField() category = models.CharField() class QuestionRating(models.Model): rating = models.OneToOneField(Rating, primary_key=True) question = models.CharField() These models model a missing question by a missing row instead of a null value which, as far as I know, is best practice. I would like to expose these models through a single API endpoint with a Django REST Framework ViewSet. On serialization the serializer should add a 'question' field only if a QuestionRating exists, and on deserializiation it should create/update the QuestionRating only if a 'question' field is provided; What would be the best way to accomplish this with a DRF serializer?