Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Connecting a Symptom Object to and Identity Object in my Health App
I am creating a Health App that will take the Identity, Symptom, Disease and Treatment of the patient. I have created models: Identity, Symptom, Disease, Treatment. I am using form.ModelForm so that I can save the data to the db i.e. sqlite3. I have created class based views that will handle forms, take field values, sanitize the data, and render the required form and values. Problem: Each time I attempt to save values for the Symptom form it seems to save it, and redirect to a new form but I am not seeing it in the Admin Backend. Code: Model document from django.db import models from django.utils import timezone import datetime class Identity(models.Model): NIS =models.CharField(max_length = 200, primary_key = True) timestamp = models.DateTimeField(auto_now = True) first_name = models.CharField(max_length = 80, null = True) last_name = models.CharField(max_length = 80, null = True ) contact = models.CharField(max_length = 15, null = True) location = models.CharField(max_length = 100, blank = True) birthday= models.DateField(auto_now = False, auto_now_add = False, blank = True, null = True) def __str__(self): return '%s, %s' % (self.first_name ,self.last_name) class Symptom(models.Model): condition_name = models.CharField(max_length = 80, default = '') description = models.TextField(max_length = 1000, default = '') def __str__(self): return … -
Updating attributes based on existing fields from view in Django
I'm using Django to write an application for short URL generator. It generates a short key to be used as short URL when concatenated with the domain name. In the view, the passed key is used to fetch record from the database and redirect the user to that specific URL. While calling the view, I want to update the visit counter on the object instance of the model. This is how my app/views.py is class ShortUrlView(RedirectView): permanent = False query_string = False pattern_name = 'short-url' def get_redirect_url(self, *args, **kwargs): short_url_obj = ShortUrl.objects.find_key(kwargs['key']) if short_url_obj is not None: // update counter is model function to update counter short_url_obj.update_counter() return super().get_redirect_url(*args, **kwargs) else: raise Http404 Now, I have to write code for update_counter() function in the model so that it could be called using a model object just like save(). I can do this in the view itself by updating the visit_counter field and then call save() on it. But how to write the function in the model, as there will no parameter passed in the function call? -
Ordering by sum of difference
I have a model that has one attribute with a list of floats: values = ArrayField(models.FloatField(default=0), default=list, size=64, verbose_name=_('Values')) Currently, I'm getting my entries and order them according to a sum of all diffs of another list: def diff(l1, l2): return sum([abs(v1-v2) for v1, v2 in zip(l1, l2)]) list2 = [0.3, 0, 1, 0.5] entries = Model.objects.all() entries.sort(key=lambda t: diff(t.values, list2)) This works fast if my list of entries is very slow. But I'm afraid with a large number of entries, the comparison and sorting of all the entries get slow since they have to be loaded from the database. Is there a way to make this more efficient? -
Celery: how to get current progress of task-group without blocking?
I'm using Django, Celery, and django-channels. I do have a working solution, it's an OK solution, except that it seems very weird to me. What I'm trying to do is this: update client of a task progress, asynchronously while also updating other elements in the client. Here is my working solution, which actually doesn't utilize groups: task_group = [refresh_func.s(user_profile, search, dont_auto_add) for search in searches] for task in task_group: task.delay() result_dict = { 'type': 'results_update', 'completed':task_group.index(task) + 1, 'total': search_len, } Group(user_profile).send( { 'text': json.dumps(result_dict), } ) Yes, I'm not wrapping my list comprehension with group because if I do I can't iterate on tasks like I do above. See my failed attempt below. My main gripe with this solution is that it really doesn't indicate anything about the task's completeness. It will update the completed count regardless of whether the task was successful. I've scoured Celery's docs and StackOverflow on how to use the group primitive, specifically, their results, quoting: >>> from celery import group >>> from tasks import add >>> job = group([ ... add.s(2, 2), ... add.s(4, 4), ... add.s(8, 8), ... add.s(16, 16), ... add.s(32, 32), ... ]) >>> result = job.apply_async() >>> result.ready() # have … -
Django get_absolute_url in inclusion_tag Issue in Template
The error I'm getting is: NoReverseMatch at / Reverse for 'view_page' not found. 'view_page' is not a valid view function or pattern name. Basically I have a template tag for my app to display the navigation menu on each page, which is dynamic so I can't hard-code the links. I've written an inclusion tag and template: from django import template from ..models import Page register = template.Library() @register.inclusion_tag("tags/page_links.html") def page_links(): all_pages = Page.objects.all() return {'pages': all_pages} And the template tag html in the templates/tags directory: <ul> {% for page in pages %} <li><a href="{{ page.get_absolute_url }}">{{ page.link_name }}</a></li> {% endfor %} </ul> Each page object has an @permalink get_absolute_url() function to get the link. This works fine in other parts of the site but this inclusion tag does not. I'm using it like so: {% load static %} {% load page_tags %} ... <p><b>Navigation:</b></p> {% page_links %} ... But it appears that the pages are having trouble using the view_page view (which otherwise works) in the template tag. What am I missing here? -
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 )