Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting Django Rest Framework to get postdata from specific post variable
I am building a Django application with a Vue.js 2 SPA. This means that everything has to be done using AJAX calls. In my case, these are handled with axios. To make things easier, I have found a Form class for ES6 online. This allows me to have a reusable form object that I can easily submit and still handle the Promise like if I was doing it directly with axios. The form class looks like this: import Errors from './Errors'; export default class Form { /** * Create a new Form instance. * * @param {object} data */ constructor(data) { this.originalData = data; for (let field in data) { this[field] = data[field]; } this.errors = new Errors(); } /** * Fetch all relevant data for the form. */ data() { let data = {}; for (let property in this.originalData) { data[property] = this[property]; } return {data}; } /** * Reset the form fields. */ reset() { for (let field in this.originalData) { this[field] = ''; } this.errors.clear(); } /** * Send a POST request to the given URL. * . * @param {string} url */ post(url) { return this.submit('post', url); } /** * Send a PUT request to the … -
Django Rest do not show postgresql binary field in view
i have model called "Person" and i want to store profile pictures in database in postgres i use "bytea" type for storing images and in my django model i use "BinaryField" my model is like this: class Person(models.Model) name = models.TextField(blank=True, null=True) photo = models.BinaryField(blank=True, null=True) .... my Django serializer: class PersonSerializer(modelserializer): class Meta: models = Person Fields= 'all' and finaly my view : class PersonView(ModelViewSet): queryset= Person.objects.all() serializer_class = PersonSerializer my problem is that when i want to insert data django do not show "photo" field in the view what is my mistake?? -
AttributeError: Manager isn't accessible via SectionSow instances
I got following error when i used to save 'sequence number' in automatic incremented form this is my models.py class SectionSow(models.Model): section_sow_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) requirement = models.ForeignKey('requirement_sow.Requirementsow', null=True, blank=True) section_title = models.CharField(max_length=100) sequence_number = models.FloatField( default=1) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) updated_at = models.DateTimeField(auto_now=True, null=True, blank=True) created_by = models.IntegerField(default=0) updated_by = models.IntegerField(default=0) def __unicode__(self): return self.section_title def save(self, *args, **kwargs): if self._state.adding: last_id = self.objects.all().aggregate(largest=models.Max('sequence_number'))['largest'] if last_id is not None: self.sequence_number = last_id + 1 super(SectionSow, self).save(*args, **kwargs) -
Django prepend string to url
How do I prepend a string to all my urls? Say I have http://127.0.0.1:8000/articles/new/ I want to have http://127.0.0.1:8000/username/articles/new/ Without having to change all the template throughout my site. The string I want to prepend here is username based on logged in user. How to achieve this? -
NoReverseMatch error happened while redirecting to another url from views.py in django
I am trying to redirect user after the signup is done and getting the below error. Reverse for 'verificationsent' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] urls.py -- urlpatterns = [ url(r'^ciasadmin/', admin.site.urls), url("^$", views.homepage, name="home"), url(r'^account/', include('accounts.urls')), ] accounts/urls.py -- from django.conf.urls import url from . import views urlpatterns = [ url(r"^signup/$", views.signup, name="account_signup"), url(r'^verificationsent/$', views.verificationsent, name='account_verificationsent'), url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',views.activate, name='activate'), ] views.py -- return redirect('verificationsent') Full traceback Internal Server Error: /account/signup/ Traceback (most recent call last): File "C:\virtualenvs\ciasenv\lib\site-packages\django\core\handlers\exception.py", line 39, in inner response = get_response(request) File "C:\virtualenvs\ciasenv\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\virtualenvs\ciasenv\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\pyprojects\cias\ciasproj\accounts\views.py", line 41, in signup return redirect('verificationsent') File "C:\virtualenvs\ciasenv\lib\site-packages\django\shortcuts.py", line 56, in redirect return redirect_class(resolve_url(to, *args, **kwargs)) File "C:\virtualenvs\ciasenv\lib\site-packages\django\shortcuts.py", line 147, in resolve_url return reverse(to, args=args, kwargs=kwargs) File "C:\virtualenvs\ciasenv\lib\site-packages\django\urls\base.py", line 91, in reverse return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))) File "C:\virtualenvs\ciasenv\lib\site-packages\django\urls\resolvers.py", line 392, in _reverse_with_prefix (lookup_view_s, args, kwargs, len(patterns), patterns) django.urls.exceptions.NoReverseMatch: Reverse for 'verificationsent' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] [22/Aug/2017 10:22:00] "POST /account/signup/ HTTP/1.1" 500 88145 I have followed the solutions from the below SO references but didn't work. Redirect … -
best NOSQL database for django?
i'm a php developer for 7 years and python for 3 years and using [mongo,cassandra] all the time recently i just dived into django and i like it so much but i'd a BIG BIG problem with reltional/SQL databases i've googled for finding the best choice to start deploying django with an Nosql database but theres no official Django support for any NoSQL databse i found MongoEngine very unhandy! actually i don't like it what do you recommend?[on your experience] i have no problem with any NoSQL databases -
DatabaseError: ORA-04098: trigger 'USSDMGADM.DJANGO_CONTENT_TYPE_TR' is invalid and failed re-validation using ORACLE DB
C:\python-examples\hello>python manage.py syncdb Creating tables ... Creating table helloapp_msisdn Mentioned below packages in INSTALLED_APPS INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.admin', 'django.contrib.staticfiles', 'helloapp') -
Calculating difference between dates and displaying the difference dynamically in django
i have been trying to calculate the difference between dates and store it in my model and display it. I have created a model 'leave' with attributes 'fromdate','uptodate', 'calculateLeaves'.I am asking the user to enter the dates in fromdate and uptodate attributes.I want to dyanamically display the difference between these dates and store it in calculatedLeaves. class leaveCreate(CreateView): model = leave fields = ['fromdate', 'uptodate'] def calculated_Leaves(self,fromdate,uptodate,calculatedLeaves): import pdb pdb.set_trace() d0 = leave.objects.filter(fromdate=fromdate,id=id()) d1 = leave.objects.filter(uptodate=uptodate,id=id()) delta = d0 - d1 delta.save() This is the view i have Written.But it doesn't work What am i doing wrong? Please suggest anything that will help me. -
How to use JS's parameters to views.py (Django)
JS $(function(){ var count=1; $("#btn").click(function(){ count++; }) }) views.py def setparam(request): counts=range(1,count) eg. Like this I want use JS's count to view.py .How can I get it ,is it possible? -
How to display hidden field along with values using .as_hidden?
In django, We can convert a form field to hidden as shown below. {{ form.user.as_hidden }} This will display a hidden field, with name as user. But it won't assign any value to it? How we can set an initial value for this field? Tried {{ form.user.as_hidden value="1"}} But it's not working. -
how to insert records using django models then run a update query
Hi I have the following model, class members(models.Model): auto_id = models.AutoField(primary_key=True) created = models.DateTimeField(auto_now_add=True) member_name = models.CharField(max_length=25, blank=False, default='') father_name = models.CharField(max_length=25, blank=False, default='') wife_name = models.CharField(max_length=25, blank=False, default='') HID = models.IntegerField(blank=True) I am using django-rest Serializers to insert records. In above HID is a number given to each member but it may change depending upon the insertion . Eg: 1,2,3...10 HID numbers are given for 10 members Now a new member is child of 3 then his number would be 4 and 4 should become 5 till end it should update Now if a member 4 is deleted then 5 should become 4 an 6 should become 5 like that it show happen How can I implement this concept with django models and views. Note: I know the number after which the insertion should happen I can chose that person or HID -
After pip upgrade error cant import django any more - No module named Utils.version
after running pip install django-csvimport -U it for some reason uninstalled my django and also got error WindowsError: [Error 5] Access is denied: so now when I import django I get error - ImportError: No module named Utils.version What is wrong? > (rent_unit_venv) C:\Users\PAPA\DEV\rent_unit\src>pip install > django-csvimport -U > Collecting django-csvimport > Downloading django-csvimport-2.11.tar.gz (45kB) > 100% |################################| 51kB 188kB/s > Collecting django>=1.7 (from django-csvimport) > Downloading Django-1.11.4-py2.py3-none-any.whl (6.9MB) > 100% |################################| 7.0MB 116kB/s > Collecting chardet (from django-csvimport) > Downloading chardet-3.0.4-py2.py3-none-any.whl (133kB) > 100% |################################| 143kB 1.9MB/s > Collecting pytz (from django>=1.7->django-csvimport) > Downloading pytz-2017.2-py2.py3-none-any.whl (484kB) > 100% |################################| 491kB 1.0MB/s > Building wheels for collected packages: django-csvimport > Running setup.py bdist_wheel for django-csvimport ... done > Stored in directory: C:\Users\PAPA\AppData\Local\pip\Cache\wheels\29\69\de\206e3a0263d286c9300dcc833b60ba95a75919c4bb00ca78b2 > Successfully built django-csvimport > Installing collected packages: pytz, django, chardet, django-csvimport > Found existing installation: Django 1.8 > Uninstalling Django-1.8: > Successfully uninstalled Django-1.8 > Rolling back uninstall of Django > Exception: > Traceback (most recent call last): > File "c:\users\papa\dev\rent_unit\rent_unit_venv\lib\site-packages\pip\basecommand.py", > line 215, in main > status = self.run(options, args) > File "c:\users\papa\dev\rent_unit\rent_unit_venv\lib\site-packages\pip\commands\install.py", > line 342, in run > prefix=options.prefix_path, > File "c:\users\papa\dev\rent_unit\rent_unit_venv\lib\site-packages\pip\req\req_set.py", > line 790, in install > requirement.rollback_uninstall() > File "c:\users\papa\dev\rent_unit\rent_unit_venv\lib\site-packages\pip\req\req_install.py", > line 759, … -
django, template_docs project, LIBREOFFICE path, Failed to initialize LibreOfficeKit
Hello everyone I am trying to make template_docs to work following the instructions: Installation is as simple as pip install templated-docs. Don’t forget to add templated_docs to your INSTALLED_APPS Django settings. Then specify the path to LibreOffice’s program directory in your settings: TEMPLATED_DOCS_LIBREOFFICE_PATH = '/usr/share/libreoffice/program' However I am not sure about the path of libreoffice: TEMPLATED_DOCS_LIBREOFFICE_PATH = '/usr/share/libreoffice/program' In my case the software is installed here: C:\Program Files (x86)\LibreOffice 5\program Therefore I in my setting.py I added: TEMPLATED_DOCS_LIBREOFFICE_PATH = 'C://Program Files (x86)//LibreOffice 5/program' but it did not work. The error that I get is pylokit.lokit.LoKitInitializeError: Failed to initialize LibreOfficeKit -
Displaying Django BooleanFields with dropdown selection
I am looking for a way to display BooleanFields a bit differently. My code is the following: in models.py class Order(models.Model): """Variables to set the type of sauce desired""" spicy = models.BooleanField(default=False) regular = models.BooleanField(default=False) delicate = models.BooleanField(default=False) extra_delicate = models.BooleanField(default=False) How can I achieve a form where the BooleanFields display as a dropdown? So, instead of having four checkboxes (one for spicy, one for regular.. etc) I would like to have one single dropdown with choice Spicy, Regular, etc so that the user can select their sauce of choice from there, instead of having to check the related checkbox. What I have tried: I tried creating a separate model for the sauces and then linked it to the Order model through a ForeignKey field. However, this doesn't seem quite right. Thank you in advance for any suggestion. -
Configuration Using reusable Django App in project
I have followed the django tutorial for making reusable apps but I cant make it work in my project. Since I have already installed the package (django-myapp) using pip I wonder what should I change in my settings.py Before I declared the app in settings like this: INSTALLED_APPS = [ 'myapp', # Name of my app 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Since the structure of the project has changed (now there is a parent folder (django-myapp) under myapp, should I change myapp to django-myapp in settings.py? I have tried using django-myapp.myapp and django-myapp also and I always get this error: Model class myapp.models.Foo declare an explicit app_label and isn't in an application in INSTALLED_APPS. If i leave it with 'myapp' I get an import error in views as expected. Thank you for the help! -
Django: something wrong with ManyToManyField.limit_choices_to
I have a model with ManyToManyField. This field has limit_choices_to attribute which is set to callable. My problem is that this callable isn't called every time form is validated/instantiated in my view. It is called only once, after making changes in code. Django says: If a callable is used for limit_choices_to, it will be invoked every time a new form is instantiated. It may also be invoked when a model is validated, for example by management commands or the admin. The admin constructs querysets to validate its form inputs in various edge cases multiple times, so there is a possibility your callable may be invoked several times. Any ideas why it doesnt working? -
Django - can't apply migration
I'm new to django development, I'm working with Mezzanine == 4.2.2 CMS and django == 1.8 when I apply migrations, I get the following error python manage.py migrate Operations to perform: Synchronize unmigrated apps: adminactions, raven_compat, staticfiles, boot, filebrowser_safe, djrill, sitemaps, compressor, django_countries, django_extensions, rest_framework, mailchimp, grappelli_safe, thumbnail, localflavor Apply all migrations: shop, core, redirects, generic, django_comments, sessions, admin, report_builder, twitter, galleries, swingtime, sites, auth, blog, brochure, contenttypes, conf, forms, cities_light, checkout, pages Synchronizing apps without migrations: Creating tables... Running deferred SQL... Installing custom SQL... Running migrations: Rendering model states...Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/VinayManeti/Documents/hedgehog_lab_projects/backend/venv/latest_gs/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/Users/VinayManeti/Documents/hedgehog_lab_projects/backend/venv/latest_gs/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/VinayManeti/Documents/hedgehog_lab_projects/backend/venv/latest_gs/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv self.execute(*args, **cmd_options) File "/Users/VinayManeti/Documents/hedgehog_lab_projects/backend/venv/latest_gs/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "/Users/VinayManeti/Documents/hedgehog_lab_projects/backend/venv/latest_gs/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 221, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "/Users/VinayManeti/Documents/hedgehog_lab_projects/backend/venv/latest_gs/lib/python2.7/site-packages/django/db/migrations/executor.py", line 104, in migrate state = migration.mutate_state(state, preserve=do_run) File "/Users/VinayManeti/Documents/hedgehog_lab_projects/backend/venv/latest_gs/lib/python2.7/site-packages/django/db/migrations/migration.py", line 83, in mutate_state operation.state_forwards(self.app_label, new_state) File "/Users/VinayManeti/Documents/hedgehog_lab_projects/backend/venv/latest_gs/lib/python2.7/site-packages/django/db/migrations/operations/fields.py", line 51, in state_forwards state.reload_model(app_label, self.model_name_lower) File "/Users/VinayManeti/Documents/hedgehog_lab_projects/backend/venv/latest_gs/lib/python2.7/site-packages/django/db/migrations/state.py", line 97, in reload_model related_models = get_related_models_recursive(old_model) File "/Users/VinayManeti/Documents/hedgehog_lab_projects/backend/venv/latest_gs/lib/python2.7/site-packages/django/db/migrations/state.py", line 57, in get_related_models_recursive rel_app_label, rel_model_name = rel_mod._meta.app_label, rel_mod._meta.model_name AttributeError: 'NoneType' object has no attribute '_meta' -
Django Admin: variables/constants inside Django Admin that can be changed
I want to have variables/constants in Django Admin, that I can use later in code. For example API keys, Google Tag manager identification number, etc. I know I can set them in settings or other file, but this are more for marketing team and can be changed. How this can be done ? are just single record variable(not multiple - so Models is not the best solution) -
creating schemaless table in postgresql with django
My basic task is to upload a csv file and dump the data in postgresql using django. Now the problem I am facing is that how can I create a schemaless table dynamically in postgresql in django to dump the csv data into db? I have searched and find examples where we have to give attribute names while creating table but in my case I would not know what are the attributes of the uploaded csv. Please guide me how should I do it and I will be thankful if anyone can share some related links -
How to get queryset with at least one of ForeignKey objects attributes specified?
I have two models related with foreign key. class Gallery(models.Model): # some attributes class GalleryPhoto(models.Model): gallery = models.ForeignKey(Gallery, related_name='photos') approved = models.BooleanField('approved', default=False) I want to get a queryset of Gallery objects that are related with at least one approved photo. I know how to get objects, where all of the photos are approved, but it's not what I want to achieve: Gallery.objects.filter(photos__approved=True) Is there a simple way to do that? -
Move the location of a button in django forms and html
I have a 2 buttons; a sign in button and a register button. Its part of a registration form made in Django. The buttons are meant to be aligned, as in same level but they are not as seen in the picture below. How would I fix this? image of problem from the html: <div class="card-content"> <form id="teacher-register-form" action="{% url 'teacher-register' %}" method="post" enctype="multipart/form-data">> {% csrf_token %} {{ form|bootstrap }} <span></span> <br/> <br/><!-- an attempt to bridge the gap between the buttons. --> <button type="submit" class="btn btn-primary pull-right">{% trans "Register" %}</button> </form> <span>{% trans "If you have an account" %}</span> <br /> <a href="{% url 'teacher-login' %}" class="btn btn-primary">{% trans "Init session" %}</a> -
Django model serializer
I am using django-rest-framework - I want to rename (in list) the field in model serializer and to update with same name which I renamed in list (to update). class ConfiglistSerializer(serializers.ModelSerializer): class Meta: model = Config fields = ('id', 'configname', 'mac_address') def to_representation(self, obj): return { 'id': obj.id, 'configname': obj.name, 'macAddress': obj.mac_address } How to update with the name ("configname" , "macAddress") in put or patch? -
django's manage.py migrate not creating relations in Heroku postgres database
Deploying a django app for the first time, and it seems like database relations aren't persisting. My makemigrations file is correct, and when running heroku run python manage.py migrate the console output suggests plenty of relations are indeed being attempted, but nothing sticks. Feels like the production environment is using sqlite3 (which means horoku is forgetting everything), but as far as I can tell I'm set up properly for postgres. Here's an excerpt of my settings from the debug page: DATABASES {'default': {'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'CONN_MAX_AGE': 0, 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'HOST': 'ec2-54-217-212-8.eu-west-1.compute.amazonaws.com', 'NAME': 'd6857svcc4kta1', 'OPTIONS': {}, 'PASSWORD': '********************', 'PORT': 5432, 'TEST': {'CHARSET': None, 'COLLATION': None, 'MIRROR': None, 'NAME': None}, 'TIME_ZONE': None, 'USER': 'hvcmnqvapkohzz'}} And the immediate problem that not having db relations is throwing up: Exception Type: ProgrammingError at /admin/ Exception Value: relation "wagtailcore_site" does not exist LINE 1: ...d_at", "wagtailcore_page"."live_revision_id" FROM "wagtailco... ^ enter code here If anyone has any ideas I'd be grateful, no doubt something obvious I'm missing here but can't spot it. -
Add in inclusion
Django 1.11.4 Below is DTL. Could you have a look at the traceback below. The problem has something to do with "|add:container_classes". If I remove it, the template doesn't blow up. Well, I experimented: 1. Printed the variable. It really prints. 2. Changed the variable to a string. Well, experiment works: template is rendered. Could you give me a kick here? template {% include 'general/inclusions/container/container_block_begin.html' with id_suffix=id classes="margin-top-10 margin-left-10 "|add:container_classes %} ...something {% include 'general/inclusions/container/container_block_end.html' with id_suffix=id%} traceback VariableDoesNotExist at /frames/2/ Failed lookup for key [container_classes] in "[{'True': True, 'False': False, 'None': None}, {}, {}, {'object': <Frame: 2>, 'frame': <Frame: 2>, 'view': <frames.views.FrameDetailView object at 0x7fef6647fcf8>}]" experiment {{ container_classes }} {% include 'general/inclusions/container/container_block_begin.html' with id_suffix=id classes="margin-top-10 margin-left-10 "|add:"abracadabra" %} ...something {% include 'general/inclusions/container/container_block_end.html' with id_suffix=id%} -
How to set default text for countries on a Django form drop down
I've been trying to get this to work and have failed. I've used - help_text, blank_label, default etc which have all resulted in errors. I have a form in which you choose your nationality. The model is working fine and in the admin section too. The countries are being generated using the Django-countries package. However when I render the form the default is Afghanistan. Know I want to the default to be 'select a country' and then people choose from the drop down. The drop down itself is work beautifully. How do I do this? (PS- I've checked various questions here and they dont answer the question like: Django: Country drop down list?, set up form option as default in a drop down, django countries dropdown default etc) From form.py nationality = LazyTypedChoiceField(choices=countries, label='Nationality', required=False) from model.py nationality = CountryField(blank_label='(select country)', null=True, blank = True)