Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Elasticsearch 5.0.2 with Django 1.8 and python 3.4 Issues with indexing
I am unable to find any method to get elasticsearch 5.0.2 to pull from my mariadb table to create an index. I have tried using multiple things from Honza's video from PyCon Aus that everyone recommends but dosnt work with 5.0.2 to elasticsearch-dsl 5.0 or different answers on here but none of it would even create the index let alone mirror the data. I am using Django 1.8.15 and python 3.4 and despertly looking for some guidance on this. -
Django: ProgrammingError relation does not exists
To setup new database on heroku I tried python manage migrate and got many exceptions related to relation already exists/does not exists. So I followed the instructions here django 1.9: ProgrammingError: relation "users_user" does not exist but it didn't work. ~ $ django-admin showmigrations admin [ ] 0001_initial [ ] 0002_logentry_remove_auto_add auth [ ] 0001_initial [ ] 0002_alter_permission_name_max_length [ ] 0003_alter_user_email_max_length [ ] 0004_alter_user_username_opts [ ] 0005_alter_user_last_login_null [ ] 0006_require_contenttypes_0002 [ ] 0007_alter_validators_add_error_messages [ ] 0008_alter_user_username_max_length contenttypes [ ] 0001_initial [ ] 0002_remove_content_type_name dashboard [ ] 0001_squashed_0024_auto_20161205_2214 (24 squashed migrations) sessions [ ] 0001_initial and when I run migrate ~ $ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, dashboard, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying dashboard.0001_squashed_0024_auto_20161205_2214...Traceback (most recent call last): File "/app/.heroku/python/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: relation "dashboard_dashboards" does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.5/site-packages/django/core/management/__init__.py", line … -
Reference Other Model from Generic View
I'm having a very difficult time finding an answer for this. Maybe its possible, maybe it isn't. If I have a reference from another model, lets say model1.customer_id = 123, how can I use that reference in a listview to display model2.company_name where the primary key (also named customer_id) of the model1 model is also == 123? -
Django enterprise model history solution with m2m and before/after values
In default django's model history implementation I lack 2 features: Tracking m2m field changed Tracking model field "before" and "after" values (+ inlines in admin detail page) Maybe there is no good solutions and there is an easy way to make custom implementation of this features? Big thx for advices. -
Safari won't upload images with FileBrowser
In my Django application, I am using the third party tool FileBrowser to upload media. In the Django Admin on Chrome, and Firefox it is working fine, however in Safari it does not work. I can choose to upload an image, and finder on my mac will pop up so I can choose a file, but when I choose a file it doesn't do anything, the finder window just closes, and no image was uploaded. In the console I get this error message. TypeError: document.getElementById(jQuery(this).attr('id') + 'Uploader').clearFileUploadQueue is not a function. (In 'document.getElementById(jQuery(this).attr('id') + 'Uploader').clearFileUploadQueue(false)', 'document.getElementById(jQuery(this).attr('id') + 'Uploader').clearFileUploadQueue' is undefined) Not really sure if this is a JQuery, Flash, FileBrowser, or Safari issue. I have tried a few things with safari's preferences, and cleared my browser cache, but nothing has worked. -
Django model instance constants
I want to have constants of model instances. Simplified, this looks like this: class MyModel(models.Model): codename = models.CharField(max_length=50, unique=True) constant1 = MyModel.objects.get_or_create(codename="cool") Of course I can't do that so simple, because this code will make an attempt to put data in database before any migrations are done, or it will fail because "models aren't loaded" at some point etc etc. But I really want to have constants like this, because I find it convenient for import. Obvious workaround solution for me - is to make function, like "def constant1():..." or "def get_constant1():..." which will do the same thing, but will never cause any problems at migration stage. But I want to access my "constant1" like variable (something = constant1), not like a function (something = constant1()) Please, tell me, is there a right way to implement constants like this, or I should surrender? -
Error migrating Django 1.6 to Django 1.10 with python-social-auth
I'm new in Django. Has anyone here worked with python-social-auth? I have an application here that was made using version 1.6 of Django, and I am trying to migrate to version 1.10. It turns out I'm going through some problems, and I'm not sure if it's because of differences between versions. When I run 'python manage.py runserver', the following error occurs: socialconnections.SocialInfluence.social_auth: (fields.E300) Field defines a relation with model 'default.UserSocialAuth', which is either not installed, or is abstract. The default.UserSocialAuth class is set to INSTALLED_APPS (social.apps.django_app.default). Has anyone ever gone through something like that and have any idea why this is happening? The code snippet that gives error is as follows: social_auth = models.OneToOneField( 'default.UserSocialAuth', related_name='social_influence') Thanks in advance. -
Pytest does not rewrite AssertionError
I'm testing a Django project using pytest with the pytest-django and pytest-cov plugins and when I'm telling it to look for tests in a directory (pytest project -vv --cov --ds=proj.tests), it does not rewrite the AssertionError when it happens : def test_pytest(): > assert 2 == 3 E AssertionError However, it still always work in another directory / django app, where it is a single tests.py file, as opposed to a directory containing python files in the above case > assert rec.action == 'updater' E assert 'update' == 'updater' E - update E + updater E ? + Also, I don't know if it helps or just confuse everything, but when looking directly for the file (pytest project/core/tests/pytest.py -vv --cov --ds=proj.tests), it works as expected: def test_pytest(): > assert 2 == 3 E assert 2 == 3 It's even stranger as it worked before, and I did not touch any of its configuration (everything is the same for my colleague, allegedly he's on a way older commit). I'm using tox to automate the tests. Here's the pytest section [pytest] python_files = tests/*.py tests*.py test_*.py minversion = 3 Why does it not work anymore like it should ? Is there anyway … -
Django RestFramework Error Associate with DateTimeField Serializer on POST Request
Based on the below Serializer, Mixin, and View, I'm able to successfully retrieve JSON data via GET request (see below), but I'm receiving "AttributeError: 'NoneType' object has no attribute 'request'" when trying to perform a JSON POST via Django Restframework and I can't figure out why. Please help. I also added the TransactionDateTime model and JSON POST request that is giving me the error. I'm using Postman to send the request. Thanks in advance. My guess is that my issue is with serializers.DateTimeField, because I successfully insert data via the Django shell using the below my_date = datetime.strptime('2015-01-28 05:30:00', '%Y-%m-%d %H:%M:%S') Please see the below serializer, successful JSON that was returned via GET Request, Mixin, View, Model and POSt JSON Request that is generating the error. serializer class SimpleSerializer4(BulkSerializerMixin, ModelSerializer): user = serializers.SerializerMethodField() start_dt = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', input_formats=['%Y-%m-%d %H:%M:%S']) def get_user(self, obj): test_me = self.context.get('request') return test_me class Meta(object): model = TransactionDateTime list_serializer_class = BulkListSerializer fields = ('pk','start_dt', 'user') Successful JSON data via GET Request [ { "pk": 1, "start_dt": "2015-01-28 03:00:00", "user": "cdoe" }, { "pk": 2, "start_dt": "2015-01-28 05:30:00", "user": "cdoe" } ] Views and Mixin class DateTimeMixin(object): serializer_class = SimpleSerializer4 permission_classes = (permissions.IsAuthenticated,) class DateTimeViewSet(DateTimeMixin, generics.BulkModelViewSet): def … -
Access Children Through Parent in Django
Is there a way in Django to add children objects to the parent? I know how to retrieve children given a parent but what I intend to do is to add children to the parent so that they may be displayed in a template. I have a list of parents and each parent needs to be displayed with their children in the template. By default, I don't see in the model where I can store a reference to children in the parent object for a one to many relationship. Any help would be appreciated. Thanks. -
Database Design Address Book
I am trying to develop a mysql schema for an address book. The uncertainty I have is how to model it because, some contacts will have one phone number and one email address whereas others may have multiples of this. In the frontend I will create a button which allows users to add address fields. Right now my Model looks like this: class Person(models.Model): sex = models.CharField(max_length=32) first_names = models.CharField(max_length=64) last_names = models.CharField(max_length=64) date_of_birth = models.DateField() marital_status = models.CharField(max_length=64) nationality = models.CharField(max_length=64) address_street = models.CharField(max_length=64) address_alt_line = models.CharField(max_length=64) address_zip = models.CharField(max_length=64) address_state = models.CharField(max_length=64) address_city = models.CharField(max_length=64) address_country = models.CharField(max_length=64) phone1 = models.CharField(max_length=64) phone2 = models.CharField(max_length=64) phone3 = models.CharField(max_length=64) phone4 = models.CharField(max_length=64) phone5 = models.CharField(max_length=64) email1 = models.CharField(max_length=64) email2 = models.CharField(max_length=64) email3 = models.CharField(max_length=64) email4 = models.CharField(max_length=64) email5 = models.CharField(max_length=64) website1 = models.CharField(max_length=64) website2 = models.CharField(max_length=64) website3 = models.CharField(max_length=64) website4 = models.CharField(max_length=64) website5 = models.CharField(max_length=64) website6 = models.CharField(max_length=64) website7 = models.CharField(max_length=64) website8 = models.CharField(max_length=64) website9 = models.CharField(max_length=64) However I am aware, that this is not very DRY. Another option I have thought of is to create separate models for persons and separate ones for addresses, emails, phone numbers, websites, etc. and then make person.id the foreign key for these models: … -
Accidentally altered a built-in python program, cannot make email-related python programs
I accidentally changed a built-in python program, either one that came with my computer or came with python, and is now bugging up every time I try to make a python email program of my own (such as the one mentioned in line 1 of the error below). I have no idea how I caused this error, the furthest I can specify is that I was practicing the code of some python Youtuber. The code he had ended up being similar to this one below that I didn't program, the one with the error raised at line 47. Traceback (most recent call last): File "my_email.py", line 1, in <module> import smtplib #actual sending function File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/smtplib.py", line 47, in <module> import email.utils File "/Users/jakedobronski/Documents/email.py", line 3, in <module> from .abstract import AbstractRegexLinkResolver SystemError: Parent module '' not loaded, cannot perform relative import This is not a program that I have written and am not sure how it has been changed to become erred. I'd try the suggestions of similar articles if it didn't risk causing further damage, error, and confusion. -
Import model from app which stays below in settings.py
I faced with problem to import model from app which defined above in settings.py For example settings.py 'auction', 'callboard', so if I try to import any models in 'callboard' from 'auction' I get an error from auction.models import Auction ImportError: cannot import name 'Auction' -
Checking existing user in model and inform him about it
My django project has app which called 'Projects' with model. Model has field 'manager_of_the_project' where admin can choice existing user or users of web site. My question is how to show to these users in there personal page that they were selected by admin as the manager of the project? I just need ideas how to realise it. I will appreciate any help. -
django updating rating field for extented user
I have two models named EventUser and Rating and EventUser has oneToOne field with Rating model. class Rating(models.Model): total = models.PositiveIntegerField(blank=True, null=True) count = models.PositiveIntegerField(blank=True, null=True) average = models.DecimalField(max_digits=6, decimal_places=3, default=Decimal(0.0)) def __str__(self): return str(self.average) class EventUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) rating = models.OneToOneField(Rating, blank=True, null=True) def __str__(self): u = User.objects.get(pk=self.user_id) return u.username Now, I want to update EventUser's rating field. I setup the logic in my mind like following; When new request is arrived 1)update total field according to request 2)increment count by one 3)calculate average I think, I need to override the update method inside a serializer. I tried couple of things but, they are not working and I really stucked at this point. -
Combining model data to form url pattern
I am generating a generic list right now, with the following code: views.py class ServiceReportIndex(LoginRequiredMixin, ListView): model = TblServiceRecords context_object_name = 'all_servicereports' login_url = 'login' template_name = 'servicereport/servicereport_index.html' # queryset = TblServiceRecords.objects.all() def get_context_data(self, **kwargs): context = super(ServiceReportIndex, self).get_context_data(**kwargs) context['companies'] = TblCompanies.objects.all() # .order_by("-date_entered")[:200] return context In my template, I want to generate a URL using both of the models. The TblServiceRecords model contains a column that references the company_id, which is the primary key of the appropriate company in the TblCompanies model. I want to use the company_name from the Companies model in my list view. How would I go about doing that? I'm sure it's simple but I can't seem to get my url tags done correctly. <div class="col-sm-4"> <p>Company Name</p> {% for servicereport in all_servicereports %} <p><a href="{% url 'servicereport:servicereport_detail' servicereport.sr_id %}">{% for servicereport.company_id in companies.company_id %} {{ companies.company_name }} {% endfor %}</a></p> {% endfor %} </div> -
How to create mutliple select in custom Django admin form?
I have a custom filter in django admin interface class ClipExcludeRightsFilter(ListFilter): title = 'rights' parameter_name = 'exclude_rights' template = 'admin_mod/filters/exclude_rights.html' def lookups(self, request, model_admin): result = ( ('avod', 'avod'), ('svod', 'svod'), ('est', 'est'), ('tvod', 'tvod') ) return result def queryset(self, request, queryset): if self.value(): urls_owner = ClipRestriction.objects.exclude(vod_system=self.value()).values_list('clip_id', flat=True) return queryset.filter( pk__in=urls_owner ) And in interface it returns list (select) and I can select just one attribute. But I need to implement multiple select. I found, that default template for this is template/admin/filter.html {% load i18n %} <h3>{% blocktrans with filter_title=title|capfirst %} By {{ filter_title }} {% endblocktrans %}</h3> <select class="combobox"> {% for choice in choices %} <option{% if choice.selected %} selected{% endif %} value="{{ choice.query_string|iriencode }}" >{{ choice.display }}</option> {% endfor %} </select> Maybe I need to write my own template but no idea how to (I need to filter selected options instantly). -
Sending an array to Django via ajax
I am trying to send a JavaScript array to Django via ajax, as follows. JavaScript: var arr = [1, 2, 3, 4]; var formData = new FormData(); formData.append('arr', arr); $.ajax({ url: '...', type: 'POST', data: formData, processData: false, contentType: false }) And on the server side, if I retrieve the data with: arr = request.POST.get('arr') the result is a string: '1,2,3,4'. However, if I retrieve the data with: arr = request.POST.getlist('arr') the result is a list containing a string: ['1,2,3,4'] How can I get a real list like [1, 2, 3, 4]? -
Dokku Django - 404 Serving media files in production using storage plugin
I'm using the official (Dokku storage plugin). I have set up a simple Django project, with a model that has an ImageField. I can upload an image via the /admin, but when I try to access it after that, I get: The requested URL /media/some_media_file.png was not found on this server. I know the file is there, because I've checked both the host and the container. This is the storage mounted path: dokku storage:list hellodjango hellodjango volume bind-mounts: /var/lib/dokku/data/storage/hellodjango:/app/storage These are my MEDIA settings: MEDIA_ROOT = '/app/storage' MEDIA_URL = '/media/' What am I doing wrong? I'm using Dokku 0.7.2 and Django 1.10 -
Using Just-Commited Data In Python Django Database
just want to know if this possible? in my views.py @login_required(login_url='/customer/sign-in/') def customer_order_new(request, menu_id): form = OrderForm() forms = NewOrderForm() formMenu = Menu.objects.get(id = menu_id) if request.method == "POST": form = OrderForm(request.POST) forms = NewOrderForm(request.POST) if form.is_valid() and forms.is_valid(): orders = form.save(commit=False) orders.customer = request.user.customer orders.restaurant = formMenu.restaurant orders.total = formMenu.price orders.status = 1 orders.save() ordet = form.save(commit=False) ordet.order = request.user.customer.orders ordet.save() return redirect(customer_order) return render(request, 'customer/form_order.html', { "form": form, "forms": forms, "menus": menu_id }) forms.py - just in case for reference class OrderForm(forms.ModelForm): class Meta: model = OrderDetails exclude = ("order", "sub_total") class NewOrderForm(forms.ModelForm): class Meta: model = Order exclude = ("customer", "restaurant", "driver", "total", "status", "created_at", "picked_at") So in my view.py could be easily seen I commited the orders, and then use it in the next line. I am not sure how to access that one too anyway. Currently with those, I got this error. Strange Is it allowed? And how can I access it? -
Postgres doesn't search case-insensitive unicode regex
I have absolutely two same databases on localhost and webfaction (I'm usin Django). The problem with server database is that it doesn't search case insensitive unicode strings. I have row name Яблоко I write Word.objects.filter(name__iregex=r'(яблоко)') and it gives me 0 rows. On localhost above query works. I tried to create database with utf8 encoding, but it didn't help. ASCII symbols work well, though. Also, if row in database is lower-cased, then it works. For example name груша will be returned (on both machines) for Word.objects.filter(name__iregex=r'(груша)') Any ideas? -
Django forms ChoiceField: how to add data attributes to input radios?
I have a form with a choicefield: class CheckoutForm(forms.Form): shipping_method = forms.ChoiceField(widget=forms.RadioSelect) How can I add data attributes to every choice? Something like: <ul id="id_shipping_method"> <li> <label for="id_shipping_method_0"> <input class="form-control" id="id_shipping_method_0" name="shipping_method" type="radio" value="C" data-method="courier"> Express courier</label></li> <li> <label for="id_shipping_method_1"> <input checked="checked" class="form-control" id="id_shipping_method_1" name="shipping_method" type="radio" value="yy" data-method="shop">In shop</label></li> </ul> -
How to include the default TEMPLATE_CONTEXT_PROCESSORS in the new TEMPLATES setting in Django 1.10
I'm upgrading a project to Django 1.10 and it has code like the following: from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP TEMPLATE_CONTEXT_PROCESSORS = TCP + ( 'django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.request', ) As far as I can tell this was a common pattern when using previous versions of Django to ensure that the default context processors. In Django 1.10 TEMPLATE_CONTEXT_PROCESSORS was removed in favour of the TEMPLATES setting which should now be defined something like this: TEMPLATES = [ { ..., 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', ... ], }, }, ] How should the TEMPLATES setting be defined to properly match the behaviour of the first code sample, i.e. ensuring that the default context processors are always included? Should I just manually include whatever was in django.conf.global_settings before? Does Django 1.10 have defaults defined anywhere? Are there any new context processors which should probably be included by default? -
Heroku isn't creating tables on my server application
I've an app running on an heroku webserver. I need to migrate the tables I've created into the server. To do this, I used the command bellow: heroku run -a ontologica python manage.py migrate The output I got was: Running python manage.py migrate on ⬢ ontologica... up, run.7044 (Free) Operations to perform: Apply all migrations: CustomUser, account, admin, auth, contenttypes, sessions, sites, socialaccount Running migrations: Applying contenttypes.0001_initial... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0001_initial... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying CustomUser.0001_initial... OK Applying account.0001_initial... OK Applying account.0002_email_max_length... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying sessions.0001_initial... OK Applying sites.0001_initial... OK Applying sites.0002_alter_domain_unique... OK Applying socialaccount.0001_initial... OK Applying socialaccount.0002_token_max_lengths... OK Applying socialaccount.0003_extra_data_default_dict... OK That's look fine. but when I execute the command to create a superuser, I got the following message: Running python manage.py createsuperuser on ⬢ ontologica... up, run.2397 (Free) You have 21 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): CustomUser, account, admin, auth, contenttypes, sessions, sites, socialaccount. Run 'python manage.py migrate' to apply them. Username: No tables was created at all. What is wrong? What … -
Joins not working in Django
I`m trying to write an inner join from two models, but I stuck in between. My models.py page is: class MovieDetails(models.Model): moviename = models.CharField(max_length=200) movieid = models.CharField(primary_key=True, max_length=20) def __str__(self): return self.movieid class TheaterBase(models.Model): theatername = models.CharField(max_length=500) theaterid = models.CharField(primary_key=True, max_length=20) def __str__(self): return self.theaterid class MovieActiveDays(models.Model): moviedetails = models.ForeignKey(MovieDetails, on_delete=models.CASCADE) theaterbase = models.ForeignKey(TheaterBase, on_delete=models.CASCADE) activedayid = models.CharField(primary_key=True, max_length=20) def __str__(self): return self.activedayid In My Views.py page: moviedetails_id = MovieActiveDays.objects.filter(theaterbase=theaterid, ).values('moviedetails_id') result= MovieDetails.objects.filter(movieid=moviedetails_id) The First line filters the movies depending upon the theaters. The second line will fetch more than 1 row from the database. And whenever I try to sent the result to html template then it prints only the moviedetails_id but not the name of the movie or its contents. How do I need to print all the contents of the moviedetails table. Thanks in advance