Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Mezzanine and MySQL: unicode errors
During a mezzanine default setup (via pip) with the MySQL backend, I see unicode errors after I choose to install the included examples. sudo pip install mezzanine ... sudo -u mezzanine python manage.py createdb --noinput This produces the following error, which traces back to 4-byte unicode entities. MySQL's default unicode only supports 3-byte entities. But when I go and set they tpe to utf8mb4 (the 4-byte MySQL UTF-8), I hit this error instead: django.db.utils.OperationalError: (1071, 'Specified key was too long; max key length is 767 bytes') The question is this: doesn't anyone use Mezzanine's examples with MySQL? If you do, how do they configure the database, and what version of Mezzanine and of MySQL are you using? -
upload image to django rest
In my ionic 2 app, I am using django rest as backend. And, I have an event model like following; class Event(models.Model): name = models.CharField(max_length=50) date = models.DateField(null=True) start = models.TimeField(null=True) location = models.CharField(max_length=255) creator = models.ManyToManyField(User, related_name='event_creator') info = models.CharField(max_length=255, default='') users = models.ManyToManyField(EventUser, blank=True) image = models.ImageField(upload_to='Images/', default='Images/None/No-img.jpg') def __str__(self): return self.name Now, I want to upload an image from phone's photo gallery, to do that I used camera plugin and now Users are able to select photo from their gallery. Camera.getPicture(options) .then(file_uri => { this.selectedImage = "data:image/jpeg;base64," + file_uri, this.imageChosen = 1 }, err => { this.selectedImage = ''; console.log(err)}) I know I have to use File transfer plugin to upload selectedImage but, I couldn't figure it out. Also, I have no idea what should I do on backend. I mean, how can I handle serializers and views to catch this uploaded image. -
How to make parallel HTTP requests to Django within the same session?
Lets say I have a webpage with 3 tables which I load through ajax. I make 3 async ajax calls, but since they are coming from the same session, they are actually run one after another on the server, not in parallel as I would like. I don't need to worry about concurrent data corruption, the 3 requests are completely independent read only requests, I only need the session to verify if the user is still logged in. So the question is: how do I make the real parallel http requests on nginx + uwsgi + django stack for the same user session? If it's indeed not possible, what would be the best way to make it possible? I searched everywhere for any hints, and I see people saying it is a limitation of: nginx, uwsgi, django, python, a browser, a programmer, without any real answers how to solve it. -
Django can't assign to ip address on google compute engine
I might be asking a dumb question but I have been stuck on this for a quite some time now. I am running a Linux VM instance on google compute engine and installed Django in it. I have reserved a static ip address using networking but when I try to run python manage.py runserver [my ip address]:8080 but i get this error: Error: That IP address can't be assigned to. I know it has something to do with my ip address configuration. I believe somehow, django is not able to reach my ip address. Does anyone know what to do? How do I configure this properly (in google console, VM or otherwise) to get this running? Any suggestions will be highly appreciated. -
Why does django loaddata fail silently for custom user model?
We have a generic super model class: class UUIDObject(models.Model): id = SimpleUUIDField(primary_key=True, default=uuid.uuid4) objects = InheritanceManager() UUIDObject uses InheritanceManager from model_utils and SimpleUUIDField which is a simple specialization of Django's UUIDField with more tolerance regarding string values. UUIDObject permits retrieval of a model instance by id without having to worry about the model type. The User model for the app inherits from UUIDObject thus: from django.contrib.auth.models import AbstractUser, UserManager as DjangoUserManager from model_utils.managers import InheritanceManager class UserManager(InheritanceManager, DjangoUserManager): pass class User(AbstractUser, UUIDObject): objects = UserManager() To preserve development users over re-factors, we keep a fixture of the devs for convenience. This is readily created with e.g django-admin.py dumpdata core.user --indent 2 > devs.json and the resulting file looks correct. When reloaded with e.g django-admin.py loaddata devs, the loading of the fixtures is reported as successful but the objects do not get added to the tables. When I use the verbose flag, it indicates that each user record in the fixture is being added twice (that sorta makes sense - one for the root table and one for the dependent table) but no actual entries appear in either table. It seems that loaddata is just failing silently and reporting success. -
How to arrive endtime using starttime and duration in django model
I have a model like this; starttime = models.TimeField('Show Start Time', ) duration = models.DurationField('Duration',) endtime = models.TimeField('Show End Time (Optional)',blank=True, null=True ) with the starttime and duration I am trying to arrive the endtime while storing the object; def save(self, *args, **kwargs): startdelta=timedelta(hours=self.starttime.hour,minutes=self.starttime.minute,seconds=self.starttime.second) enddelta = startdelta + self.duration self.endtime = enddelta super(Showsets, self).save(*args, **kwargs) Above code throws me error, I want to know how the timefield and duration field works in django also please assist with the ways to query the fields based on starttime or endtime (like objects that starts (starttime) in 30mins from now). Also curious to know if there are any django-app(add-ons) for time based querying. Thanks a ton! -
Django's annotate Count with division returns integer instead of float
I have many objects and 3 of them have name='AAA' I group them by 'name' and annotate num in group: my_models = MyModel.objects.order_by('name').values('name').annotate(count=Count('name')) for i in my_models: print(i.count, i.name) I get: 3, 'AAA' 1, 'BBB' ... Everything is fine, but when I try to add some formula to annotate Count(): my_models = MyModel.objects.order_by('name').values('name').annotate(count=Count('name') / 2) I get: 1, 'AAA' 0, 'BBB' ... But expected: 1.5, 'AAA' 0.5, 'BBB' ... -
Django post_save signal acts like pre_save
I'm trying to create a simple signal which creates an identifier for the model. class Scheduler(models.Model): weekhours = models.ManyToManyField('WeekHour', related_name='schedulers') identificator = models.TextField(null=True,blank=True) class WeekHour(models.Model): hour = models.PositiveSmallIntegerField(verbose_name='Hour in week (0 - 7*24') Everytime when Scheduler object is saved, I want to create or update the identificator joining a list of [weekhour_obj.hour for weekhour_obj in scheduler.weekhours.all()] So I created a post_save signal. The problem is that when I save Scheduler, the signal acts like it was pre_save. The workhours set for the scheduler is the old one, not updated. When I save it second time it works. @receiver(post_save,sender=models.Scheduler) def set_identificator(sender,created,instance,**kwargs): identificator = ','.join([str(x.hour) for x in instance.weekhours.all().order_by('hour')]) models.Scheduler.objects.filter(pk=instance.pk).update(identificator = identificator) Do you know where is the problem? EDIT - Example: When I put print instance.weekhours.all() to the first line in the signal method it acts this way: Created a scheduler object in Django admin with weekhours with hour 2 and hour 4. It printed nothing. Opened scheduler in admin and changed WeekHours from 2 and 4 to 5. It printed <QuerySet [<WeekHour: 2>,<WeekHour: 4>]> Opened scheduler again and changed weekhours to 6 and 7. It printed <QuerySet [<WeekHour: 5>]> But it is a post_save signal so why it acts like … -
Overriding save method raises exception when object is created
I'm trying to create an identificator for my Scheduler model which depends on ManyToManyField of this model. The problem is that when I override save method, the first time (when object is created) it causes problems. It should be saved first. On the other hand when I create a post_save signal, the problem is that I have to save the model inside this signal which ends with infi class Scheduler(models.Model): weekhours = models.ManyToManyField('WeekHour', related_name='schedulers') identificator = models.TextField(null=True,blank=True) def save(self,*args,**kwargs): if self.weekhours.all(): identificator = ','.join([str(x.hour) for x in self.weekhours.all().order_by('hour')]) self.identificator = identificator super(Scheduler, self).save(*args, **kwargs) ValueError: "<Scheduler: None>" needs to have a value for field "scheduler" before this many-to-many relationship can be used. Do you have any ideas? -
mysqldump from within python script but command not found
I need to execute mysqldump from within a django function. I can do so easily enough from the terminal command line, but when I try to run it from within the python script, I get an error: sh: mysqldump: command not found when running the following. filestamp = date.today() dumpcmd = "mysqldump -u root appdb > appdb%s.out" % (filestamp) os.system(dumpcmd) I think the problem has something to do with the Path in either the django application or Eclipse, but I can't figure out why mysqldump can't be found from within the django app but it can be from the command line / virtualenv -
Mutiple site architecture
Im going to be building 3-4 sites for a few businesses for myself. They'll be CMS sites basically. My idea is to use django rest and maintain a single admin across the sites, then serve react apps from the fronend via nginx at different domain urls. Does this sound like an easy, sane way of approaching this? If i were doing a single site id be inclined to use nodejs with keystonejs framework, and frankly i like node more, but it doesnt seem easy to have multiple sites with a single admin. Thanks -
JSON Web Token expiration and remember me functionnality
I am starting to work on an authentication system for an angular 2 Single Page Application using django-rest framework as back-end. I'd also like to have some kind of "remember me" functionality that is going to keep users logged in for a certain amount of time. From what I have read so far, it seems that the best authentication method for this kind of Angular 2 SPA/REST API is using jwt (json web token). For jwt authentication, I looked at the django-rest-framework-jwt (https://github.com/GetBlimp/django-rest-framework-jwt). The problem that I see is that the token needs to have a short life span (few minutes to a few hours...) in order to minimize security issues if the token get stolen. The token now needs to be refreshed frequently to avoid the user from being disconnected while using the application. In this case, a "remember me" functionality is posing problem since the token have a short life span. I thought about a solution involving a second token that would serve as a refresh token. It would be opaque, have a longer life span and would contain information specific to the user (ip address or something like that) so that if it get stolen, the information … -
Querying a model based on user input in Django
I am new to Django and I am trying to build a basic search/filter feature; for example, a basic version of the refine/filter part on amazon while searching for products. (I am using Sqlite3 in development) I think I could implement a filter in which you could click part of a form and it would return a page with the database items that match the query, however, I am not sure on how I could do this if the search contained more than one part to the query, for example if the search was to find a book that was published before 2010 and costs more than £4.99, I am unsure on how to do this. I am looking to build a checkbox type of filter rather than a search like google. This sort of filter/search All help is appreciated, Thank You. -
Django template rendering beckground-image
My view send to my template one object with this value: http://dominio/rota/id/original/(nome)8.jpg In my templete I have: <div style="background-image: url( ' {{ obj.url }} ' )"></div> When my template is rendered it looks like this: background-image: url(' http://dominio/rota/id/original/(nome)8.jpg ' ); Error: Invalid property value This happens because inside the URL there is a ")" that encloses the value of the url () How can I solve this? I tried the following combinations in the template, without success: <div style="background-image: url( {{ obj.url }} )"></div> <div style='background-image: url( " {{ obj.url }} " )'></div> <div style="background-image: url( ' {{ obj.url }} ' )"></div> <div style='background-image: url( {{ obj.url }} )'></div> -
Filter objects by manytomany relation
Can't figure out a good way to filter by many to many relation. class Scheduler(models.Model): weekhours = models.ManyToManyField('WeekHour', related_name='schedulers') def get_active_products_by_weekhour(self,weekhour): return Product.objects.filter(scheduler__in=WeekHour.objects.get(hour=weekhour).schedulers.all()) class WeekHour(models.Model): hour = models.PositiveSmallIntegerField(verbose_name='Hour in week (0 - 7*24') Now suppose I have a list of numbers, for example: hours = [2,4,60,66] I want to find a Scheduler which has this exact set of WeekHour objects with these hour values. Is this possible using Django orm and not using cycles? EDIT: What about this? weekhours_set = [Weekhour.objects.get(hour=x) for x in hours] scheduler = Scheduler.objects.filter(weekhours__exact=weekhours_set) -
Updating user information from separate model Django
I'm creating a simple weight management application where users can register, login and update information such as weight, body measurements etc. I've not used Django for a little while and slowly learning best practices from where i left off a little while ago. I'm using the django-allauth to manage the user registration as this allows people to login with Facebook etc. I've created a simple app called 'Stats' with a ForignKey to the Users. class Stat(models.Model): user = models.ForeignKey(User, default=False) height = models.CharField(max_length=20) weight = models.CharField(max_length=20) waist = models.CharField(max_length=20) hips = models.CharField(max_length=20) upperleg = models.CharField(max_length=20) upperleg = models.CharField(max_length=20) calf = models.CharField(max_length=20) bodyfat = models.CharField(max_length=20) What i would like the user to be able to do is login and update stats on a daily / weekly basis. Then to be able review previous stats. This will probably be done via a model form based on the above approach. I will add more complexity as time goes on. Is there another way to do that would have any advantages? If the best approach is the best? Is there a way i can list all the objects from that model inside the users page in the admin to be able to reviews users … -
ValueError at /new_topic/ Cannot assign "<SimpleLazyObject: <django......>": "Topic.owner" must be a "User" instance
*Any time i insert data the above error occurred! * # my views def new_topic(request): """Add a new topic.""" if request.method != 'POST': # No data submitted; create a blank form. form = TopicForm() else: # POST data submitted; process data. form = TopicForm(request.POST or None, request.FILES or None) if form.is_valid(): new_topic = form.save(commit=False) new_topic.owner = request.user #this where i think, i'm messing up! new_topic.save() return HttpResponseRedirect(reverse('learning_logs:topics')) context = {'form': form} return render(request, 'learning_logs/new_topic.html', context) *model representing each Topic * from django.contrib.auth.models import User def upload_location(instance, filename): return "%s/%s" %(instance.id, filename) class Topic(models.Model): """A topic the user is learning about""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) image = models.ImageField() height_field = models.IntegerField(default=0) width_field = models.IntegerField(default=0) owner = models.ForeignKey(User) def __str__(self): """Return a string representation of the model.""" return self.text Any help please! -
django not loading app templates
I've look over the other SO questions related to this but none have helped. I just installed an app and added to the INSTALLED_APPS variable in settings. The app django_messages, extends a base.html template from each of its templates. For some reason django isnt recursively searching the app directory for this template. Here is the error: In template /Library/Python/2.7/site-packages/django_messages/templates/django_messages/inbox.html, error at line 1 {% extends "django_messages/base.html" %} That file is located at: /Library/Python/2.7/site-packages/django_messages/templates/django_messages/base.html but the search path django is giving is: Django tried loading these templates, in this order: Using engine django: django.template.loaders.app_directories.Loader: /Library/Python/2.7/site-packages/django_messages/templates/base.html (Source does not exist) So based on what I understand about the template loader it makes sense it should be searching /Library/Python/2.7/site-packages/django_messages/templates/ for the file. But the file is called "django_messages/base.html" so I don't understand why django is looking for base.html in django_messages/templates and ignoring the django_messages qualifier. All my other templates (in my own apps) are set up this way app_name/templates/app_name/xxx.html as indicated in the django docs. So everything looks correct but is not working. Any help appreciated tired of banging my head on this. Thanks. -
Django-Registration: Overriding the default fields
Yesterday I faced a problem trying to override the RegistrationForm of Django-Registration app. The class RegistrationForm inherit from UserCreationForm of Django, which is based on ModelForm, so I created my custom class inheriting from RegistrationForm in this way: from django import forms from django.contrib.auth.models import User class MyRegistrationForm(RegistrationForm): class Meta: model = User fields = ('username', 'email', 'password1', 'password2') widgets = { 'username': forms.TextInput( attrs={'placeholder': 'hasdsa', 'class': 'form-control'}), 'email': forms.EmailInput( attrs={'placeholder': 'hasdsa', 'class': 'form-control'}), 'password1': forms.PasswordInput( attrs={'placeholder': 'hasdsa', 'class': 'form-control'}), 'password2': forms.PasswordInput( attrs={'placeholder': 'hasdsa', 'class': 'form-control'}), } I set the Meta class in this way because the model User and the fields username, email, password1, password2 are the same attribute of UserCreationForm. This code live in a module named accounts / forms.py and is called directly from accounts / urls.py in this way: from django.conf.urls import include, url from registration.backends.hmac import views from accounts.forms import MyRegistrationForm urlpatterns = [ url(r'^register/$', views.RegistrationView.as_view(form_class=MyRegistrationForm), name='registration_register'), url(r'', include('registration.backends.hmac.urls')), ] The goal here is overriding the attributes of an input field of a form with widgets adding attributes like class or placeholder or change the labels of the form or adding error_messages and so on. As explained in Django-Registration docs to achieve this you just … -
uploading static files of django app to s3 with boto3 and storages
I know that this question has been asked a lot of times but i still can't get it to work. My Env configuration: Python 2.7 Django 1.9.5 In my requrements.txt i have the following dependencies boto3==1.4.2 django-storages==1.5.1 I have added the storages in my INSTALLED_APPS. These are my settings parameters. AWS_ACCESS_KEY_ID='****' AWS_SECRET_ACCESS_KEY='****' AWS_STORAGE_BUCKET_NAME='****' AWS_AUTO_CREATE_BUCKET = False DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage' STATICFILES_STORAGE = DEFAULT_FILE_STORAGE AWS_LOCATION = 'static/' When i run the ./manage.py collectstatic command i get the following error: File "/home/me/myproj/local/lib/python2.7/site-packages/storages/backends/s3boto.py", line 23, in <module> raise ImproperlyConfigured("Could not load Boto's S3 bindings.\n" django.core.exceptions.ImproperlyConfigured: Could not load Boto's S3 bindings. See https://github.com/boto/boto Any ideas why? what didn't i configure properly? -
Django association between three modals
I have this three modals : Person. Project. Role. Using Django modals system, How to represent the fact that a person is participating to a particular project with a specific role ? general problem : What is the proper way to handle "ternary associations" using Django ? -
How To Request: Implementing Django-Haystack Custom Forms
I've been playing around with Django for a bit now & think I've got my head around its concepts and how it functions. In order to add search to my site, I've opted for Haystack with a Whoosh backend (the database the site is based on shouldn't be too large, around 700-800 records across 3 tables at the moment). I've followed the tutorial in the Haystack documents and can successfully search with the provided out-of-the-box form. Next step to build my own custom form, and this is where I have immediately hit upon problems. Basically, I find the extant documentation to be severely lacking, and I don't see how Haystack's approach is supposed to merge with Django's general approach. I'm probably missing something straightforward, but I was hoping someone could provide me with some basic step by step instructions. From the small example in the documentation I have created my own version of this form referring to a date field in my database. I'm stuck on the next step. How do I move from this form to having it display? I have follow/looked at numerous questions (such as this this and this), but can't even figure out which url to … -
Django 1.10.3 connecting to MySQL 5.7.16
Environment: Windows 8 I am trying to connect to mysql using Django. I understand that this module is needed: 'MySQLdb'. To get this module I used pip install MYSQL-python and easy_install MySQL-Python. But I am getting the error from 1. I will have to abandon Django all together if it cannot connect to Mysql. -
Django-recurrence i18n
I'm working on Django 1.8 project and i want to use some other i18n on django-reccurence different from English. But i can't deal with it. I found different locales in recurrence/locale and i know how gettext is working but when i change my default Django language to some locale that are already presented in locale e.g. i set LANGUAGE_CODE = 'fr' admin language are changing to French language, but recurrence widget is still in English. Also i add js i18n url: js_info_dict = { 'packages': ('recurrence', ), } # jsi18n can be anything you like here urlpatterns += ( url(r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict), ) But JS widget is still use English. What am i doing wrong? -
Django ORM first() method not working with all() method?
The first() method of Django ORM is supposed to return first record of a queryset, but why is it not working with something like Publisher.objects.all().first()?