Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Ajax will not post a file (online site available for running the sample)
The website and place of doubt is online, link below. I have cloned a git site and just added one File Field to the Models.py and to the Forms.py but, as you can test, it will refuse to accept that a file has been uploaded and will not post the form because it says the field is missing the file. https://mysite-mayarodina.c9users.io/books/ The files in question> models from future import unicode_literals from django.db import models class Book(models.Model): HARDCOVER = 1 PAPERBACK = 2 EBOOK = 3 BOOK_TYPES = ( (HARDCOVER, 'Hardcover'), (PAPERBACK, 'Paperback'), (EBOOK, 'E-book'), ) title = models.CharField(max_length=50) publication_date = models.DateField(blank=True, null=True) author = models.CharField(max_length=30, blank=True) price = models.DecimalField(max_digits=5, decimal_places=2) pages = models.IntegerField(blank=True, null=True) book_type = models.PositiveSmallIntegerField(choices=BOOK_TYPES, blank=True, null=True) book = models.FileField("none.jpg") the jquery that executes the code $(function () { /* Functions */ var loadForm = function () { var btn = $(this); $.ajax({ url: btn.attr("data-url"), type: 'get', dataType: 'json', beforeSend: function () { $("#modal-book .modal-content").html(""); $("#modal-book").modal("show"); }, success: function (data) { $("#modal-book .modal-content").html(data.html_form); } }); }; var saveForm = function () { var form = $(this); $.ajax({ url: form.attr("action"), data: form.serialize(), type: form.attr("method"), dataType: 'json', success: function (data) { if (data.form_is_valid) { $("#book-table tbody").html(data.html_book_list); $("#modal-book").modal("hide"); } else { … -
more pythonic way to test
Ok I'm writing tests for my Django app. I'm trying to figure out a way to iterate over the testing for a ajax register call for the appropriate responses. It's working but I know it can be done in a more efficient way. def test_ajax_register(self): c = Client() # Check register success response = c.post('/register/', { 'register-username': 'testuser', 'register-email': 'testuser@email.com', 'register-password': 'password' }) self.assertEqual(json.loads(response.content)['status'], 'success') self.assertEqual(response.status_code, 200) # Check register failed username taken response = c.post('/register/', { 'register-username': 'testuser', 'register-email': 'testuser@email.com', 'register-password': 'password' }) self.assertEqual(json.loads(response.content)['status'], 'fail') self.assertEqual(json.loads(response.content)['error_msg'], 'username already in use') # Check register failed email in use response = c.post('/register/', { 'register-username': 'testuser1', 'register-email': 'testuser@email.com', 'register-password': 'password' }) self.assertEqual(json.loads(response.content)['status'], 'fail') self.assertEqual(json.loads(response.content)['error_msg'], 'email already in use') # Check register failed password length response = c.post('/register/', { 'register-username': 'testuser2', 'register-email': 'testuser2@email.com', 'register-password': 'pass' }) self.assertEqual(json.loads(response.content)['status'], 'fail') self.assertEqual(json.loads(response.content)['error_msg'], 'password must be atleast 8 characters long') -
ValueError: Cannot create form field for 'author' yet, because its related model 'settings.AUTH_USER_MODEL' has not been loaded yet
I am trying to set up a basic blog with a custom auth model. I am trying to get a simple form to work but somehow I am not able to make it work. I am not sure what is causing the error. This is a fresh app and a fresh project I am working on. I tried to reference from the docs but I am not sure what I am doing incorrect. How can i fix this error? Thanks in advance Docs: https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#changing-to-a-custom-user-model-mid-project Similar questions: Cannot create form field for 'created_by' yet, because its related model 'users.User' has not been loaded yet My Current Code models.py class User(AbstractUser): pass class Post(models.Model): author = models.ForeignKey('settings.AUTH_USER_MODEL') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) image = models.ImageField(upload_to=get_image_path, verbose_name='Image', null=True,blank=True) forms.py: from blog.models import User class PostForm(forms.ModelForm): image = forms.CharField( widget=forms.FileInput(attrs={'class': 'form-control'}),required=False) class Meta(): model = Post fields = ('author','title', 'text','image') widgets = { 'title': forms.TextInput(attrs={'class': 'textinputclass'}), } views.py from blog.forms import PostForm, CommentForm class CreatePostView(LoginRequiredMixin,CreateView): ... form_class = PostForm model = Post ... settings.py: AUTH_USER_MODEL = 'blog.User' admin.py: from .models import User from django.contrib.auth.admin import UserAdmin admin.site.register(User,UserAdmin) -
The best model configuration for Audits Platform in Django 1.11
I am creating an Audits Platform using Django 1.11 There will be one big form with questions and answers. And I would like to ask you ,how should it works from database perspective ? Should I save each separate answer into database and for example for audit with 10 answers I should insert 10 records ? If not, how to create so elastic model to import there records depending on number of questions ? I will be very thankful for your help, Thanks in advance, -
CSS rule isn't applied
I have the following CSS: workoutcal.css: .errorlist{ color:red; } the following base template: base.html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}Default Title{% endblock %}</title> <link rel="stylesheet" href="{% static 'css/workoutcal.css' %}"> </head> <body> {% block content %}{% endblock %} {% block footer %}{% endblock %} <div class="hidden" id="hidden"> {% block hidden %}{% endblock %} </div> </body> </html> and the following template that inherits from it: {% extends "workout/base.html" %} {% block content %} <h1>Register new user</h1> <form action="/workoutcal/register/" method="post"> {% csrf_token %} {{ form.non_field_errors }} {% for field in form.visible_fields %} <div class="row"> <div class="col-xs-2"> {{ field.label_tag }} </div> <div class="col-xs-2"> {{ field }} </div> <div class="col-xs-3"> {{ field.errors }} </div> </div> {% endfor %} <input type="submit" value="Register"> </form> {% endblock %} If there are any errors, they will lead to <ul> elements with the .errorlist class being rendered in the browser: <div class="row"> <div class="col-xs-2"> <label for="id_username">Username:</label> </div> <div class="col-xs-2"> <input type="text" name="username" value="sahand" maxlength="150" required id="id_username" /> </div> <div class="col-xs-3"> <ul class="errorlist"><li>A user with that username already exists.</li></ul> </div> </div> I want the text in this ul-list to be red, as I've tried to make it with the rule in my CSS. The … -
Django get total count of each choicefield in template
Example model: SOURCE_CHOICES = ( 'PH': 'PHONE', 'OT': 'OTHERS ) class Test(models.Model): source = models.CharField(..., choices=SOURCE_CHOICES) I am able to get to total count of each item in Model choice by using the following queryset: Test.objects.values('source').annotate(Count('source')) It gives me the following output: <QuerySet [{'source': 'PH', 'lead_source__count': 5}, {'lead_source': 'OT', 'lead_source__count': 4}]> Below is what I want to show in the template: Phone: 5 Others: 4 How can I achieve this? So far I have tried the following in the template: {% for src in source %} {% for k, v in src.items %} {{v}} {% endfor %} {% endfor %} It gives me the below output: PH 5 OT 4 -
Form field validation causes problems for multi-field validation
I'm writing a register user form where I am implementing some of my own password validation (checking if the password chosen by the user is complex enough). So far I've only implemented one requirement, that the password needs to be long enough. If the password fails on this requirement, the whole site crashes. Let me explain why. Here's the form: class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) confirm_password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['username','email','password'] def clean_password(self): password = self.cleaned_data['password'] if len(password) < 8: raise forms.ValidationError(_('The password needs to be at least 8 characters long')) return password def clean(self): cleaned_data = super(UserForm, self).clean() password = cleaned_data['password'] confirm_password = cleaned_data['confirm_password'] if not password == confirm_password: raise forms.ValidationError(_('The passwords do not match')) and here's the error: File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/workout/workoutcal/forms.py", line 43, in clean password = cleaned_data['password'] KeyError: 'password' When the clean_password() method raises the error, it doesn't return the password, which causes it to go missing from the self.cleaned_data dictionary. I could think of one way to solve this problem: def clean(self): cleaned_data = super(UserForm, self).clean() try: password = cleaned_data['password'] confirm_password = cleaned_data['confirm_password'] if not password == confirm_password: raise forms.ValidationError(_('The passwords do not match')) except KeyError: pass This way, if there is … -
I continuously receive `Invalid HTTP_HOST header` error email after I upgrade my django site from http to https
Recently, I upgrade one of my django sites from http to https. However, after that, I continuously receive Invalid HTTP_HOST header error email while before I never received such type of emails. Here are some log messages: [Django] ERROR (EXTERNAL IP): Invalid HTTP_HOST header: '123.56.221.107'. You may need to add '123.56.221.107' to ALLOWED_HOSTS. [Django] ERROR (EXTERNAL IP): Invalid HTTP_HOST header: 'www.sgsrec.com'. You may need to add 'www.sgsrec.com' to ALLOWED_HOSTS. [Django] ERROR (EXTERNAL IP): Invalid HTTP_HOST header: 'sgsrec.com'. You may need to add 'sgsrec.com' to ALLOWED_HOSTS. Report at /apple-app-site-association Invalid HTTP_HOST header: ‘sgsrec.com’. You may need to add ‘sgsrec.com’ to ALLOWED_HOSTS. Invalid HTTP_HOST header: ‘www.pythonzh.cn’. You may need to add ‘www.pythonzh.cn’ to ALLOWED_HOSTS. Report at / Invalid HTTP_HOST header: ‘www.pythonzh.cn’. You may need to add ‘www.pythonzh.cn’ to ALLOWED_HOSTS. Request Method: GET Request URL: http://www.pythonzh.cn/ Django Version: 1.10.6 [Django] ERROR (EXTERNAL IP): Invalid HTTP_HOST header: 'pythonzh.cn'. You may need to add 'pythonzh.cn' to ALLOWED_HOSTS. What the strange thing is that I only change my blog site www.zmrenwu.com nginx configuration, but seems all of my sites which hosted on 123.56.221.107 are effected. Nginx configuration of my blog site www.zmrenwu.com: server { charset utf-8; server_name zmrenwu.com www.zmrenwu.com; listen 80; return 301 https://www.zmrenwu.com$request_uri; } server … -
Why DoesNotExist while query is exist?
I dont know what is wrong with this code. But I actually want to get my query so I use User.objects.get(pk=mail) while the mail is an string that I got from request.POST.get('email') . I try to access my data through the Django Shell, it working fine. but I dont know. here is the code in models.py: class User(models.Model): email = models.EmailField(max_length=150, primary_key=True) pw = models.CharField(max_length=255) in views.py: if request.method == 'POST': mail = request.POST.get('email') pwd = request.POST.get('pw') a = User.objects.get(pk=mail) Thanks in advance. -
Use new subclass with already in use database in django
I'm trying to create a customized User class inheriting from django User. Problem is I already have some users in database which can not be deleted whatsoever and also I have another class (let's say reports) which have a foreignkey to User. My question is: Is there any way to create my new User class and keep the old data too? thanks in advance. -
auto_now_add only if value if empty in django
I have datetimefield that I want to create an automatic record of the date only if I did not specify a value for it, because sometimes i put a specific date The code : record_date = models.DateTimeField(auto_now_add = True) I try with "editable = True" but it is the same result How can I impose this condition? -
Django save object in database
First of all I should mention that I'm new to Python as well as Django. I have a Django project with an sqlite3 database. I have created a couple of classes for calculating some physical problems, and I want to access the result of these through my website using forms. My previous approach to this was to change my classes to functions, and create several model fields for my objects. Then I reached a point where the output of my function was a 2D-array, which I have issues saving in my model. So I decided it would be easier just to store the entire object in the database - then I wouldn't have to change my classes to functions in order to utilize it in Django. I'm using inputs for my calculations in a form, a and b below. Is it possible to store objects in my model? I have made a hypothetic example, not sure if the code works but hope that you get the point. class Butterfly_model(models.Model): a = models.FloatField(verbose_name='a') b = models.FloatField(verbose_name='b') results = >>>Some_Object_Field<<< my computation script could contain something like this: class Compute: def __init__(self, a, b): self.X=[] self.Y=[] for i in range(0,a): self.X.append(i) self.Y.append(i+b) … -
Django - Nearest shops you
I'm trouble, anybody can help me please? I've been using this example http://www.rkblog.rk.edu.pl/w/p/shops-near-you-geographic-features-geodjango/, but in Django 2.0 and I don't getting success, don't shows any error but doesn't work, my code is: PS: In my github is https://github.com/rafaelribeiroo/magalu-finder Models.py from django.db import models from django.contrib.gis.db import models as gis_models from django.contrib.gis import geos from urllib.error import URLError from geopy.geocoders import GoogleV3 class Produto(models.Model): # codigo = models.IntegerField() # Não tem sentido o atributo acima, uma vez que o # Django gera um ID automático name = models.CharField('Nome', max_length=50, blank=False) value = models.DecimalField( 'Valor', max_digits=7, decimal_places=2, blank=False) description = models.TextField( 'Descrição', max_length=999, blank=False) class Meta: ordering = ['id'] verbose_name = 'Produto' verbose_name_plural = 'Produtos' def __str__(self): return self.name class Loja(models.Model): product = models.ManyToManyField(Produto, verbose_name='produtos') filial = models.IntegerField('Código Filial', blank=False) cep = models.IntegerField('CEP', blank=False) address = models.CharField(max_length=100) city = models.CharField(max_length=50) # Qual a diferença entre Blank e Null? # O argumento BLANK servirá apenas para validar os inputs # Já o NULL, para o banco de dados location = gis_models.PointField( 'Longitude/Latitude', geography=True, blank=True, null=True ) description = models.TextField( 'Descrição simples', max_length=500, blank=False) gis = gis_models.Manager() objects = models.Manager() class Meta: ordering = ['filial'] verbose_name = 'Loja' verbose_name_plural = 'Lojas' def __str__(self): return … -
Django: Timefield widget not showing in template
TLDR: how do I get my timefield to show in the template? I customized my ModelForm in the class meta. For some reason, only the label change is shown, not the widget change. Here is my code: class MenuCreateForm(forms.ModelForm): class Meta: model = Menu fields = ( 'name', 'monday', 'availability_begin_mon', 'availability_end_mon', labels = { 'availability_begin_mon': ('Begin Montag'), 'availability_end_mon': ('Ende Montag'), widgets = { 'availability_begin_mon': forms.TimeInput(format='%H:%M'), 'availability_end_mon': forms.TimeInput(format='%H:%M'), And here is the template I used: <form method="POST"> {% csrf_token %} {{ form.as_p }} <button class="btn btn-primary" type='submit'>Änderungen speichern</button> </form> Does anyone have an idea? Thank you very much! -
AttributeError at /api/project/ 'Query' object has no attribute 'query_terms' tastypie
class Project(models.Model): project_name = models.CharField(max_length=100,default=None) user = models.ForeignKey(User, on_delete=models.CASCADE) intro = models.TextField(default=None) start_date = models.DateField() end_date = models.DateField() def __str__(self): return self.project_name class UserResource(ModelResource): class Meta: class ProjectResource(ModelResource): user = fields.ToManyField(UserResource, 'user', full=True) class Meta: queryset = Project.objects.all() resource_name = 'project' allowed_methods = ['post', 'get'] authorization = DjangoAuthorization() Newbie in tastypie, When i follow the documents i get attribute error on api url (api/project/) dont know the meaning of query_terms, tried searching , thanks in advance -
How to get value to one html page to another in Django?
I just began to work with Django and I would like to create a submit form in a html form that communicates with another html page. Page1.html : Submit form, let's suppose I type "Hello world" then I click on submit, I'm redirected to page2.html Page2.html : Thanks to the Get request Page2.html display "Hello World" because the page2 has been loaded from page1 In page1 I use this form : <form type="get" action="/page2" style="margin: 0"> <input id="search_box" type="text" name="search_box" placeholder="Search..." > <button id="search_submit" type="submit" >Search</button> In Views.py I have this function : def page2(request): if request.method == 'GET': search_query = request.GET.get('search_box', None) return render(request, 'interface/recherche.html', locals()) But I don't know how to display how the word that has been typed in page1 in page2, thank you very much for your answer :) -
Django- Password Validation in ModelForms
I have created a ModelForm for registration of user. Under the Meta class I have defined a function clean(self) to validate the password and show error if password is not valid. But it's not working well. It works fine whenever I enter a pssword that is less than 8 characters. If I enter a password with no numeric character, it gives no error at all. And if I enter a password which isn't same to the confirm_password, it redirects to the error page which says, Forbidden (403) CSRF verification failed. Request aborted. Please tell me where I am wrong. forms.py: class user_form(forms.ModelForm): password = forms.CharField(widget = forms.PasswordInput) confirm_password = forms.CharField(widget = forms.PasswordInput) class Meta: model = User fields = ['username','email', 'password','confirm_password'] def clean(self): password1 = self.cleaned_data.get('password') password2 = self.cleaned_data.get('confirm_password') errors=dict() if password1 and password1 != password2: raise forms.ValidationError("Passwords don't match") try: password_validation.validate_password(password=password1,user=User) except exceptions.ValidationError as e: errors['password']=list(e.messages) if errors: raise forms.ValidationError(errors) return self.cleaned_data register_form.html: <form method="post" action=""> {% csrf_token %} {% include 'one/form-template.html' %} <button type="submit"> create account </button> </form> form_template.html: {%for field in form%} <div class="popup"> {{ field.errors }} </div> <label>{{field.label_tag}}</label> <div> {{field}} </div> {%endfor%} -
Django UnicodeDecodeError only on apache/nginx
When locale.getlocale() locale.getdefaultlocale() sys.getfilesystemencoding() sys.getdefaultencoding() is run through manage.py shell, I get ('en_US', 'UTF-8') ('en_US', 'UTF-8') utf-8 utf-8 Which fits my locales: LANG=en_US.UTF-8 LANGUAGE=en_US: LC_CTYPE="en_US.UTF-8" LC_NUMERIC="en_US.UTF-8" LC_TIME="en_US.UTF-8" LC_COLLATE="en_US.UTF-8" LC_MONETARY="en_US.UTF-8" LC_MESSAGES="en_US.UTF-8" LC_PAPER="en_US.UTF-8" LC_NAME="en_US.UTF-8" LC_ADDRESS="en_US.UTF-8" LC_TELEPHONE="en_US.UTF-8" LC_MEASUREMENT="en_US.UTF-8" LC_IDENTIFICATION="en_US.UTF-8" LC_ALL=en_US.UTF-8 However, when the request is handled by Apache/Nginx it produces: (None, None) (None, None) ascii utf-8 This leads to several UnicodeDecodeErrors throughout my site and I failed to find the reason for the mismatch. Neither setting AddDefaultCharset utf-8 for Apache or charset utf-8; for Nginx solved the issue. -
Am I safe to copy my settings.py file which was generated offline to my remote server?
So I'm moving my project from my offline directory to my remote server on Digital Ocean. Is there anything I need to be concerned about? For example am I safe keeping the same SECRET_KEY that was generated offline? Anything else I need to worry about? -
Html Tagging in to Django tagging
How to convert Simple Html into Django, Template? (In Django, template compiler is considering block tagging as a text not as a tag ) -
pdf report genrate in python 2.7
https://dpaste.de/RosE check this link. i write a code for pdf file report genrate. but face error.Kindly check my code. Any solution for me tell me Thanks -
Celery & Django: calling completed_count() floods workers?
I'm trying to get the progress of a Celery task group, called like so in consumers.py: searches = [s.strip() for s in query.split(',') if s.strip()] task_group = group([refresh_func.s(user_profile, search, dont_auto_add) for search in searches]) result = task_group.apply_async() result_waiting = result.waiting() This is all happening inside a Django channels, utilizing daphne and websockets, but that shouldn't matter too much. In order to poll the current task-group completed count, and return it to the client, I'm doing this later in consumers.py: while result_waiting: result_dict = { 'type': 'results_update', 'completed': result.completed_count(), 'total': search_len, } Group(user_profile).send( { 'text': json.dumps(result_dict), } ) if result.completed_count() == len(searches): result_waiting = False It's working fine, except that relative to the time the mission itself takes - it's also painfully slow. The tasks in the group are completed in seconds, but .completed_count() takes from 20-50 seconds to show the right completed tasks count. If I add time.sleep(0.1) at the end of the while loop above, The results update much faster, but that seems like an anti-pattern. What is going on here? Am I utilizing completed_count wrong? Is it overloading the workers, the websocket? -
Job completing in Celery terminal but returns false in Django
I have the following code in my Ajax View: def ajax_view(request, task_id): results = convert_to_nightcore.AsyncResult(task_id) print(task_id) if results.ready(): return render_to_response('download_ready.html', {'results': results.get()}) return render_to_response('not_ready.html', {}) This is in my urls.py url(r'^result/(?P<task_id>.*)$', views.ajax_view, name='result') This is the result of my task in celery: [2017-12-16 09:08:38,534: INFO/MainProcess] Received task: nightcore.tasks.convert_to_nightcore[cd1b19fd-f721-4fa1-b9db-1ce01738d030] [2017-12-16 09:08:38,536: INFO/ForkPoolWorker-2] Task nightcore.tasks.convert_to_nightcore[cd1b19fd-f721-4fa1-b9db-1ce01738d030] succeeded in 0.00173856299989s: '/home/student/PycharmProjects/tonightcore/media/uploads/The_Skeptic_in_the_Room-OPs_j1EEplI_3O4k7JT.mp3' The task prints out the value it is supposed to print. This is the printed out value of print(task_id) in my Ajax View: [16/Dec/2017 09:11:19] "GET /result/cd1b19fd-f721-4fa1-b9db-1ce01738d030 HTTP/1.1" 200 22 cd1b19fd-f721-4fa1-b9db-1ce01738d030 As you can see the values are the same, but when I query http://127.0.0.1:8000/result/cd1b19fd-f721-4fa1-b9db-1ce01738d030, it returns the not_ready.html while it is supposed to return download_ready.html -
Django: Unknown column 'last_login' in 'field list'
I did look through other topics but I couldn't find anything useful or that would help me. All I did was doing python manage.py inspectdb > models.py and then edit the file a bit, the user model and then did migrate. Now when I try to create a super user I get this error D:\Programming\Web\blaine county\website>python manage.py createsuperuser --username=andrei --email=andreigames9@gmail.com Password: Password (again): This password is too short. It must contain at least 8 characters. Password: Password (again): Traceback (most recent call last): File "D:\Programming\Python\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "D:\Programming\Python\lib\site-packages\django\db\backends\mysql\base.py", line 71, in execute return self.cursor.execute(query, args) File "D:\Programming\Python\lib\site-packages\MySQLdb\cursors.py", line 250, in execute self.errorhandler(self, exc, value) File "D:\Programming\Python\lib\site-packages\MySQLdb\connections.py", line 50, in defaulterrorhandler raise errorvalue File "D:\Programming\Python\lib\site-packages\MySQLdb\cursors.py", line 247, in execute res = self._query(query) File "D:\Programming\Python\lib\site-packages\MySQLdb\cursors.py", line 411, in _query rowcount = self._do_query(q) File "D:\Programming\Python\lib\site-packages\MySQLdb\cursors.py", line 374, in _do_query db.query(q) File "D:\Programming\Python\lib\site-packages\MySQLdb\connections.py", line 277, in query _mysql.connection.query(self, query) _mysql_exceptions.OperationalError: (1054, "Unknown column 'last_login' in 'field list'") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "D:\Programming\Python\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "D:\Programming\Python\lib\site-packages\django\core\management\__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Programming\Python\lib\site-packages\django\core\management\base.py", line 288, … -
email field for authentication in django2.0
i create new project on Django 2.0 and DRF, my need use email field for users authentication. How better do it, write authentication backend or use similar code class MyUser(AbstractUser): USERNAME_FIELD = 'email' email = models.EmailField(_('email address'), unique=True) thanks in advance