Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Fix Label Matching of Django Forms Checkboxes with Multiple Copies of a Form
I have a Django Form that contains a checkbox: class ExampleForm(forms.Form): checkbox = forms.BooleanField(required=False, label="Click me") I have multiple of this form on a page: {% for item in items %} <form> {{ ExampleForm }} </form> {% endfor }% When I click the label of one of the lower forms, the checkbox in the top form is the one that toggles. How do I fix the label matching so that the correct instance of the checkbox is clicked? -
Django app not working externally on Windows Server
I am trying do deploy Django application on Windows Server 2008 using IIS. By default in IIS some exemplary page were set on localhost on port 80. And the page were working both on the server and on some computer connected to the server. So everything was fine. Later I did the steps described on Matt Woodward's Blog and set my django application on localhost on port 80 (I deleted the default page). It works on server. But when I connect from external computer I get white page with only two words invalid request. I know that I did not post many details, but maby you have some idea why the first page works fine and the second (django) works only on server. I guess it's not a problem with firewall (the first page worked). I will appreciate any help. -
Boolean annotation resulting in duplicates?
I am trying to implement a basic 'favourites' system based on a foreign key table. Let's say I have the following simple models: class Item(models.Model) id = models.IntegerField() class User(models.Model) id = models.IntegerField() class UserFavourites(models.Model) user = models.ForeignKey(User, related_name='user_for_fav_rel') item = models.ForeignKey(Item, related_name='item_for_fav_rel') Now I generate the following queryset for items to see if they have been marked as a favourite by the user: queryset = Item.objects.all() USER_ID = request.user.id queryset.annotate( favourite=Case( When( item_for_fav_rel__user__id=USER_ID, then=Value('True') ), default=Value('False'), output_field=BooleanField() ) ) All of this works great, but in the response, if the item has indeed been favourited, I receive a duplicate of that particular item in the queryset. Any idea how to avoid this? -
http request in Django Channels
I am starting with Django channels. In views.py in normal http protocol I have request.POST and I can render some html files. I know that consumers.py are like views.py, so how can I modify sent message and render some html files? For example I want paste some text click some button to send it, modify it and print on screen everything via Websocket. Thank You! -
convert unix timestamp to datetime in a django query model
I need to compare two sets of fields. One field is in datetimestamp format, the other is in unix timestamp. One of them obviously needs to be convert to the other to compare. How can I achieve this without doing loops or modifying my actual models? My best effort: user = User.objects.annotate(photo_time=F('date_joined')) similar_user = similar.extra(select={'photo_time': "FROM_UNIXTIME(UNIX_TIMESTAMP(),'%Y %D %M %h:%i:%s %x')"}) -
Use reactjs in existing django application instead of django templates
I have an already running project on django that uses basic django templates to render html pages. I want to start using react to handle only some of the UI part while the rest part will still be rendered with django templates only (e.g header and footer section will be rendered through django templates only). I don't want to use node for this purpose. I am new to django, Can anyone please help me and guide how to install react in existing django project? -
django migrations to PostgreSQL not handling order_with_respect_to removals
If you change the Meta fields on a model to remove an order_with_respect_to tag, it creates a command in the new migration file like thus: migrations.AlterOrderWithRespectTo( name='entry', order_with_respect_to=None, ), and everything works hunky-dory for SQLite. However... push your new code and migration files to a PostgreSQL server, like Heroku, run your migration file and ... ERROR 2017-11-22 16:51:18,081 exception 8 140423074580224 Internal Server Error: DETAIL: Failing row contains (276, , 2017-11-22, U, 9, 1, null, ). This little friend starts filling your log files. What does it mean? Well, a little exploration of the database tables show that the second last field that django is trying to assign null value to is the _order field. _order field I'm presuming is only used by the order_with_respect_to tag. It doesn't seem to be created when a order = ['score'] command is used. So it seems somewhere in the process it realises the _order field isn't needed, is assigning a null value to that column which clashes with a no null constraint. All when it should have simply deleted the _order field column after the migration was run. An incompatibility bug between django and PostgreSQL perhaps? Insights anyone? -
How to use Django template tags while passing them to a javascript function in HTML?
My template tag {{ session.time }} returns Nov. 24, 2017, 2 p.m, for say one session. My HTML code for this part looks something like this {% if sessions %} {% for session in sessions %} <div id="item" onload="check_time('{{ session.time }}')"> <li id="abc"> Tutor: {{ session.tutor.user_profile.user.first_name }} {{ session.tutor.user_profile.user.last_name }}</li> <li>{{ session.time }}</li> {% if session.tutor.is_contracted == 0 %} <li> Charged Amount: {{ session.amount }}</li> {% endif %} <li id="yo"><button class="btn btn-primary">Cancel</button></li> </div> {% endfor %} {% endif %} And my script looks something like this... alert("Hi!"); var current_hours = new Date().getHours(); function check_time(hour) { alert("fsdjnfkjsbdkfjbsdkjfbskjdfb"+hour); } I want to know when calling check_time function in onload of the division can how do I pass the template tag {{ session.time }} -
Django Image is not saving in database
I'm trying to upload a user photo and show it in homepage. problem 1 : When i upload an image from admin section it gets saved in database but it doesn't show up in 'homepage.html'. Problem 2 : When i try to upload an image using 'profile.html' template the image is not even saved in database. I've tried several solution from stackoverflow but failed to solve my problem. My code is given below: models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') first_name= models.CharField(max_length=100, default='', blank=True) last_name = models.CharField(max_length=100, default='', blank=True) email = models.CharField(max_length=100, default='', blank=True) pro_pic = models.ImageField(upload_to='profilepic',blank=True) phone = models.CharField(max_length=20, blank=True, default='') city = models.CharField(max_length=100, default='', blank=True) country = models.CharField(max_length=100, default='', blank=True) job = models.CharField(max_length=20, blank=True, default='') organization = models.CharField(max_length=100, default='', blank=True) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() forms.py from django.contrib.auth.models import User from django import forms from .models import UserProfile class UserForm(forms.ModelForm): class Meta: model = UserProfile fields = ['first_name', 'last_name', 'email'] class ProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ['pro_pic','phone', 'city', 'country', 'job', 'organization'] settings.py … -
PostgreSql Connection with Django
I have connected my Postgresql database with django, by giving these parameters in django settings file DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'TryDjango', 'USER':'postgres', 'PASSWORD':'postgres', 'HOST':'localhost', 'PORT':'5432', } } and i have created Post table in models file class Post(models.Model): Title = models.CharField(max_length=200) Content = models.TextField() updated_on = models.DateTimeField(auto_now=True,auto_now_add=False) created_on = models.DateTimeField(auto_now=False,auto_now_add=True) def __str__(self): return self.Title I run python manage.py makemigrations and python manage.py migrate everything run fine there were no errors, when i checked Postgresql db there are tables Post_post auth_group auth_permission etc so when i am running query select * from Post_post; there is an error ERROR: relationship "post_post" does not exists help me out, with this problem. -
Authorization Token is not being received by Django server from ios - React native
When i do a request using Fetch (in ios) from a react native app, with a Django backend, the header Authorization Token is not being received, but the others headers are. I try using nc -l 8090 just to check out if the app was sending correctly the header and it was there. Also, this just happens in the ios version, the android one works just fine. At checking the Django backend, the Authorization Token is not being received ( I printed what i got in the authentication.py file ) I put the fetch code here: let response = fetch('http://xxx.xxx.x.xxx:8000/' + 'users', { method: 'GET', headers: { 'content-type': 'application/json', 'x-app-key': xxxxxxxxxx, 'Authorization': 'Token xxxxxxxxxxxxxxxxxxxx' } }).then((response) => {...} The error message that im getting in the response is 403 django standar not valid authentication. Im not using OAuth2. Any other information that could provide, please let me know and thank you for any help. -
DjangoRestFrameWork filter one model from another
I have a model with an ArrayField called "participants". I can't have the array be a list of users due to the limitations of postgress' ArrayField. Due to this, I have stored the usernames as strings in the array. Now I want to serialize the user ID, and username class ConversationSerializer(serializers.ModelSerializer): class Meta: model = c.Conversation lookup_field = 'uid' fields = ( 'uid', 'participants', 'archived', ) Is there anyway I can return the user ID's of the participants instead of the strings? So instead of the below result: { "uid": "dd51b07d-06f2-481a-b68d-fa18e9959392", "participants": [ "userJohn", "userDave" ], "archived": false } I could get the user model fields: { "uid": "dd51b07d-06f2-481a-b68d-fa18e9959392", "participants": [ { 'username': 'userJohn', 'id': 4, }, { 'username': 'userDave', 'id': 5, } ], "archived": false } -
Django how does a dictionary with an queryset as value work?
Hey i can´t help me please explan me why i can interate over an value form an dictionary key. And Please tell me how to build this kind of dictoinary on my own. I want to build an dictionary in my View that can interatet over just like below with multiple values per key. My database Model: class DB(models.Model): titel = models.CharField(max_length=2000) text = models.CharField(max_length=2000) My View all_db_entrys = DB.objects.all() context = { 'all_db_entrys':all_db_entrys } (...) return HttpResponse(template.render(context, request)) My template {% for item in all_db_entrys %} <li>{{ item.id }} {{ item.titel }} {{ item.text}}</li> {% endfor %} Browser 1 test test1 2 test test2 3 foo bar -
Django set Initial data in Forms
I am new to Django, Let say I have a view like follow with form class DepartmentCreateView(LoginRequiredMixin,CreateView): form_class = DepartmentForm template_name = os.path.join(TEMPLATE_FOLDER, "create/index.html") def get_success_url(self): position_id = self.kwargs.get('position_id') return reverse_lazy('departments_list', kwargs = { 'college_id' : college_id }) def get_initial(self): initial = super(DepartmentCreateView, self).get_initial() initial.update({ 'college' : self.kwargs.get('college_id'), 'code' : 1 }) return initial my form looks like class DepartmentForm(forms.ModelForm): class Meta: model = Applicant fields = ('name', 'college', 'code') I used the get_initial() to set the default value in college field of DepartmentForm, it works fine on the first time(GET REQUEST), but if I submit the form with invalid data, Form shows the error messages correctly, but the value for college is not set to default which is returned from get_initial(). what mistake i made here? -
Django - variable value, TypeError
I created a tag like this: @register.inclusion_tag('post/comment_block.html') def limit_amount_in_a_page(page_nr=1, post_id=1, amount=5): starting_index = page_nr*amount for index in range(starting_index, starting_index + amount): dosomething() has_prev = (page_nr != 0) has_next = ((page_nr + 1) * amount) < comments.count() return { something } The problem is : page_nr is always not an int. and this is how I call the tag and assign the value to page_nr in the tag: {% limit_amount_in_a_page page_nr=my_page_nr post_id=post.id amount=4 %} this is where the value of my_page_nr comes from: def to_post_page(request, post_id, page_nr): post = get_object_or_404(Post, id=post_id) form = CommentForm() comments = Comment.objects.filter(pk=post_id) return render(request, 'post/posts.html', { 'post': post, 'form': form, 'comments': comments, 'my_page_nr': page_nr, }) this is the url calling the view: url(r'^(?P<post_id>[0-9]+)/(?P<page_nr>[0-9]+)/$', views.to_post_page, name="post"), {% for post in my_posts %} <li><a href="{% url 'forum:post' post.id 0 %} ">{{post.title}}</a></li> {% endfor %} The value passed to this url tag should be a int. As you can see, I passed a 0. Really appreciate for any help! -
Django returning serialized data from django-reversion version object into original object works extremely slow
I am working with a django-reversion to store object`s versions and then return a queryset with all objects that related to some date state. The revert method doesn`t suite for me, because It affects original data in a database. So to achieve a goal, I have created BaseModel class where provided additional functionality. With the code below I can get a queryset of objects that correspond to some date without actually changing original data in the database: import reversion import datetime selected_datetime = datetime.datetime(2017, 11, 22, 23, 59, 59) class BaseModelQuerySet(models.QuerySet): def get4date(self, DateTime): ex_id = [] if self.exists(): for obj in self: check = obj.get4date(DateTime) if check is None: ex_id.append(obj.id) return self.exclude(id__in = ex_id) class BaseModelManager(models.Manager): def get_queryset(self): return super().get_queryset().get4date(selected_datetime) class BaseModel(models.Model): objects = BaseModelManager.from_queryset(BaseModelQuerySet)() def get4date(self, DateTime): # find the most recent version for a given date: versions = Version.objects.get_for_object(self).filter(revision__date_created__lte=DateTime) if versions.exists(): version = versions.first() for k,v in self.__dict__.items(): if k in version.field_dict and k != "id": continue return self return None def save(self, *args, **kwargs): with reversion.create_revision(): super().save(*args, **kwargs) class Meta: abstract = True Then, I can do something like the code below in models.py: @reversion.register class ModelOne(BaseModel): ...fields @reversion.register class ModelTwo(BaseModel): modelone = models.ForeignKey(ModelOne) @reversion.register class … -
Trying to set timezone to EST in Django
I want to set my django app to work with all times in EST. I seem to be missing something about how to set this up? >>>from django.conf import settings >>>print settings.USE_TZ True >>>print settings.TIME_ZONE EST >>>from django.utils import timezone >>>timezone.now() datetime.datetime(2017, 11, 22, 16, 40, 50, 893000, tzinfo=<UTC>) -
django/wagtail model - if ForeignKey wagtailimages.Image field is saved blank, then save default
I am saving a model for a BlogPage(Page) and want to allow author to input image, but if they choose not to, automatically save a specific image. Here is my model: from django.db import models from core.models import Page from modelcluster.fields import ParentalKey, ParentalManyToManyField from modelcluster.tags import ClusterTaggableManager from wagtail.wagtailimages.edit_handlers import ImageChooserPanel class BlogPage(Page): date = models.DateField('Post Date') categories = ParentalManyToManyField('blog.BlogCategory', blank=True) tags = ClusterTaggableManager(through=BlogPageTag, blank=True) feed_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) Would the best way to set a ForeignKey on save() be by: def save(self, *args, **kwargs): if self.feed_image = None: self.feed_image = something? super(BlogPage, self).save(*args, **kwargs) if so, what is the expected input of something? an image url? Or is it cleaner to set a default on the ForeignKey, like: feed_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, default=something? on_delete=models.SET_NULL, related_name='+' ) if so, what would is the expected format of that something?? I know this logic can be done in the template, but it interferes and if possible, I'd like it to be done in the model. Thanks! -
Task handler raised error: ImproperlyConfigured Database
I have Django project with completely functioning ORM for Postgres. And I have integrated celery, and on Task.on_failure I need to store failure details on my Postgres database. I have inherited the parent Task.on_failure method as: class CustomTask(celery.Task): def on_failure(self, exc, task_id, args, kwargs, einfo): FailedEmail.objects.create(message='message') print "CustomTask on the failure world" @app.task(bind=True, max_retries = 1, base=CustomTask) def send_mail(self, subject, message, from_address, to_address, bcc_address=""): try: raise smtplib.SMTPException except BaseException as exc: self.retry(exc=exc, countdown=2) But I am getting error on that above Task call; send_mail.delay('subject', 'message', 'from@xyz.com', 'to@xyz.com') with following message: Task handler raised error: ImproperlyConfigured('settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.',) Please find my celery_.py settings: from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'infinia_biz.settings') app = Celery('infinia_biz') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() settings.__init__.py file: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'database', 'USER': 'root', 'PASSWORD': 'root', 'HOST': 'localhost', 'PORT': '', } } CELERY_IMPORTS = ['libs.tasks'] CELERY_TASK_REJECT_ON_WORKER_LOST = True CELERYD_TASK_SOFT_TIME_LIMIT = 60 from .celery_ import app as celery_app __all__ = ['celery_app'] Those celery related Task is not configured with my database settings. I am something missing over here? -
Django: Model inheritance from abstract models based on condition
In my model there is an option field recursion_period: class RecurringMeeting(models.Model): RECURSION_OPTIONS = ( ('daily', 'Daily'), ('weekly', 'Weekly'), ) recursion_period = models.CharField(max_length=50, choices=RECURSION_OPTIONS) Based on the value of the recursion_period value I would like to inherit fields from either the DailyMeeting or the WeeklyMeeting abstract models: class DailyMeeting(models.Model): # some fields here class Meta: abstract = True and class WeeklyMeeting(models.Model): # some other fields here class Meta: abstract = True Would it be possible to choose which model to inherit based on the value of the recursion_period field? -
python-django/python manage.py runserver error
I am trying to run the server using this command(python manage.py runserver) but i am getting this error even i have installed mysqlclient and mysql-python C:\Users\neethu\sencha\sencha-sdks\sencha_workspace\webapp>python manage.py runserver Unhandled exception in thread started by Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python27\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models() File "C:\Python27\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "C:\Python27\lib\importlib__init__.py", line 37, in import_module import(name) File "C:\Python27\lib\site-packages\django\contrib\auth\models.py", line 4, in from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Python27\lib\site-packages\django\contrib\auth\base_user.py", line 52, in class AbstractBaseUser(models.Model): File "C:\Python27\lib\site-packages\django\db\models\base.py", line 124, in new new_class.add_to_class('_meta', Options(meta, app_label)) File "C:\Python27\lib\site-packages\django\db\models\base.py", line 325, in add_to_class value.contribute_to_class(cls, name) File "C:\Python27\lib\site-packages\django\db\models\options.py", line 214, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "C:\Python27\lib\site-packages\django\db__init__.py", line 33, in getattr return getattr(connections[DEFAULT_DB_ALIAS], item) File "C:\Python27\lib\site-packages\django\db\utils.py", line 211, in getitem backend = load_backend(db['ENGINE']) File "C:\Python27\lib\site-packages\django\db\utils.py", line 115, in load_backend return import_module('%s.base' % backend_name) File "C:\Python27\lib\importlib__init__.py", line 37, in import_module import(name) File "C:\Python27\lib\site-packages\django\db\backends\mysql\base.py", line 30, in 'Did you install mysqlclient or MySQL-python?' % e django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: DLL load failed: %1 … -
django handler404 is being called even on valid urls
I am using django 1.8. In my project urls.py I have this line: handler404 = 'config.views.handler404' And in my views.py, in the config app, the following: def handler404(request): print("Hello world!) I don't know why, but that Hello World is being printed on every request, including the ones that have a valid URL pattern. I just want that method to execute when the URL is not found (404) Is there something I am missing? -
Django adaptive form with many to many model
Thanks to the help I received on this forum i created a model to handle stocks for a laboratory. It works, but impossible to create a friendly-user interface to fully use the functionalities... The objective is to produce an Environment by doing a Preparation following a Recipe. The model Making stores relation between the theorical quantities and quantities used in practice. The models are the following (simplified) : #models.py class Product(models.Model): name = models.CharField(max_length=10) globalQuantity = models.FloatField() class Environment(models.Model): id = models.CharField(max_length=25, unique=True) volume = models.FloatField() preparation = models.ForeignKey('Preparation',null = True) class Recipe(models.Model): name = models.CharField(max_length=30) product = models.ForeignKey('Product') theoretical_quantity = models.FloatField() class Preparation(models.Model): label = models.CharField(max_length=30) make = models.ManyToManyField('Recipe', through='Making') class Making(models.Model): prep = models.ForeignKey('preparation') recipe = models.ForeignKey('recipe') real_quantity = models.FloatField() At the end we have a situation like this : Environment id = ENVI-TEST-001 | volume = 150l | preparation = Pancakes-V1.0 Recipe name = Pancakes | product = Flour | theoretical_quantity = 100g name = Pancakes | product = Eggs | theoretical_quantity = 4 Making Pancakes-V1.0 | Pancakes | Flour | theoretical_quantity = 100g | real_quantity = 98g Pancakes-V1.0 | Pancakes | Eggs | theoretical_quantity = 4 | real_quantity = 3 The idea is then to create … -
Where/how to replace default upload handler in Django CBV?
I am trying to specify a specific method of handling file uploads for a class based view. Per the docs this can be achieved by something like: from django.core.files.uploadhandler import TemporaryFileUploadHandler request.upload_handlers = [TemporaryFileUploadHandler(request=request)] If i specify this in post method of a FormView like so: def post(self, request, *args, **kwargs): self.request.upload_handlers = [TemporaryFileUploadHandler(request=self.request)] return super().post(self, request, *args, **kwargs) I get: AttributeError: You cannot set the upload handlers after the upload has been processed. Variants like yield the same result: def post(self, request, *args, **kwargs): self.request.upload_handlers = [TemporaryFileUploadHandler(request=self.request)] form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) However when i do this in the get method this is ineffective: def get(self, request, *args, **kwargs): request.upload_handlers = [TemporaryFileUploadHandler(request=self.request)] return super().get(self, request, *args, **kwargs) If I upload a small file it still uses the default django.core.files.uploadhandler.MemoryFileUploadHandler. What am I doing wrong? -
Django UpdateView extend the Form field choices
I have a Django form with a field called ipts which by default has the content choices=(('', '-'*20),). In the UpdateView I extend this list with more options. Thus, in the get_context_data I get the form and extend that list. choices = form.fields['ipts'].choices choices = choices.extend( [('IPTS-123', 'IPTS-454545'),] ) To make sure the choices was well populated, in the render_to_response method I print the form.fields['ipts'].choices and I have what I was expecting: [('', '--------------------'), ('IPTS-123', 'IPTS-454545')] However the template is not populated with these choices! Just the initial value is available for selection: ('', '--------------------') Any ideas how to extend the choices field in a Class Based View? Suggestions are welcome. Thanks.