Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Save Django Formset
Scenario i want to save multi instance at once in the page. My Solution so i decide to use Django builtin formset method. and also i want to create a link for adding new line(actually new form) to the form for better data entry in the template view. the original formset shows all the blank forms in one place , i handle dynamically adding form to formset by using 'jquery.formset.js' . this plugin let me to add new form to the page by clicking on the "add new" link. Problem i have 2 main problem with this scenario. the first one (which related to the jquery plugin) is the 'jquery.formset.js' do not show me the delete link (which generated by the formset) instead of delete checkbox jquery.formset.js turns it into a input by type=hidden , and my second problem is when i save the form in the view.py all rows saved again it means if i have two instance in the form by the submitting the new instance the old ones will be added again to the database. my codes in the models.py: class SitePlan(models.Model): name = models.CharField( max_length=255) class HeavyTruck(models.Model): name = models.CharField( max_length=255) qty = models.IntegerField() power = … -
MultiSelect field in Django
How to store multiple check-boxes data in database. If I select 5 checkboxes items then 5 rows should be inserted in DB. I don't want to represent this form's selection in my database as comma separated values. -
When upgrading from Django 1.7 - 1.8, I get ImportError: Could not import 'serve'. The path must be fully qualified
I'm upgrading my project from 1.7 to 1.8, and I'm coming up with this problem about the inability to import "serve". This is happening on all of my pages. I can't find anyone else having this error or any notes about "serve" in the release notes. Any clue what the issue is? Internal Server Error: /feed/ Traceback (most recent call last): File "C:\Users\JBLT\Envs\django18\lib\site-packages\django\core\handlers\base.py", line 164, in get_response response = response.render() File "C:\Users\JBLT\Envs\django18\lib\site-packages\django\template\response.py", line 158, in render self.content = self.rendered_content File "C:\Users\JBLT\Envs\django18\lib\site-packages\django\template\response.py", line 135, in rendered_content content = template.render(context, self._request) File "C:\Users\JBLT\Envs\django18\lib\site-packages\django\template\backends\django.py", line 74, in render return self.template.render(context) File "C:\Users\JBLT\Envs\django18\lib\site-packages\django\template\base.py", line 209, in render return self._render(context) File "C:\Users\JBLT\Envs\django18\lib\site-packages\django\template\base.py", line 201, in _render return self.nodelist.render(context) File "C:\Users\JBLT\Envs\django18\lib\site-packages\django\template\base.py", line 903, in render bit = self.render_node(node, context) File "C:\Users\JBLT\Envs\django18\lib\site-packages\django\template\debug.py", line 79, in render_node return node.render(context) File "C:\Users\JBLT\Envs\django18\lib\site-packages\django\template\loader_tags.py", line 135, in render return compiled_parent._render(context) File "C:\Users\JBLT\Envs\django18\lib\site-packages\django\template\base.py", line 201, in _render return self.nodelist.render(context) File "C:\Users\JBLT\Envs\django18\lib\site-packages\django\template\base.py", line 903, in render bit = self.render_node(node, context) File "C:\Users\JBLT\Envs\django18\lib\site-packages\django\template\debug.py", line 79, in render_node return node.render(context) File "C:\Users\JBLT\Envs\django18\lib\site-packages\django\template\loader_tags.py", line 135, in render return compiled_parent._render(context) File "C:\Users\JBLT\Envs\django18\lib\site-packages\django\template\base.py", line 201, in _render return self.nodelist.render(context) File "C:\Users\JBLT\Envs\django18\lib\site-packages\django\template\base.py", line 903, in render bit = self.render_node(node, context) File "C:\Users\JBLT\Envs\django18\lib\site-packages\django\template\debug.py", line 79, in render_node return node.render(context) File … -
Customizing my model multiple choice field label doesn't populate with existing values
tl;dr Custom django form field isn't populating with existing data Issue Hopefully this is a simple problem. I have a form with a custom multiple choice field. class CustomChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return mark_safe('<b>%s:</b> <span class="context">%s</span>' % (obj.field1, obj.field2)) class MyForm(forms.ModelForm): a_field = CustomChoiceField(widget=forms.CheckboxSelectMultiple, queryset=MyModel.objects.all(), required=False) And this gets me my checkboxes in my template the way I want them, with a <span> inside the <label>. However, if this form form has an instance associated with it, the saved values from the model do not check the appropriate boxes. That is, if someone checked box1 and box3, but not box2, it renders all 3 checkboxes as unchecked, even though in the admin I can verify box1 and box3 as checked. Changing away from my custom choice field to Django's ModelMultipleChoiceField gets rid of this problem. class MyForm(forms.ModelForm): a_field = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=MyModel.objects.all(), required=False) And now in my template box1 and box3 do appear as checked. Why is my custom form field not showing existing data? -
Test API Key to return mock data with Django Rest Framework and TokenAuthentication
I'm building a REST-ful API using Django Rest Framework. I have handled integration with REST APIs before for work and have been given test API keys specifically for use with testing for integration, keys that allow you to send data and returns mock data, but doesn't put the data in the system. I am trying to implement this same feature in my API, but I haven't been able to find a way to do so yet. -
Do not forward headers in Django
I faced with the following issue yesterday: I sent a request to a Django web server, it supposed to redirect the request to amazon s3. I use query string auth to access the files. At some point, I got an error from s3 saying that only one authentication method is allowed. With the redirect, the authentication token was still in the request headers. I guess this could be a potential security issue. After some research, I figured out that Angular is not responsible for this since the redirects are handled by the browser without reaching the js layer. So if I can't set it on the client, I guess I should take care of it on the server side (although I'm not quite fond of it). My question is: using the django.shortcuts.redirect helper, is there any way to prevent forwarding certain headers (or specifically the Auth header) when redirecting to 3rd parties? Is there a global setting that I could use? -
Google StackDrive Logging Level in containers with uwsgi always at Error Level
I'm deploying via Kuberenetes come containers on Google Cloud, which are django project and uwsgi to run them. I'm using the stackdrive logging tool to see the logging, the problem is that all the entries are seen as severity ERROR even thought they are not error. It seems that the log of uwsgi is written to stderr or something like that. In the picture you can see that django uses INFO level, but that is received as ERROR by stackdrive. this is how i set up uwsgi. [uwsgi] master = true socket = :3031 chdir = . wsgi-file = docker.wsgi processes = 4 threads = 2 socket-timeout = 90 harakiri = 90 http = :8000 env = prometheus_multiproc_dir=multi enable-threads = yes lazy-apps = yes pidfile=/tmp/project-master.pid -
WinError123 when uploading images within an ImageField with django on Windows 7
I am encountering a very strange issue when I try to upload an image within an ImageField on Windows 7. I have defined the MEDIA_URL and MEDIA_ROOT in my settings.py to be the following: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'media') For the sake of simplicity, this is the relevant part of my Model: class Level(models.Model): figure = models.ImageField(upload_to='level_figures/', blank=True, null=True, default=None) I already created a Level object without a figure, and I want now to add it using the django shell: from django.core.files import File from .models import Level level = Lebel.objects.last() level.figure = File(open("C:\\Users\\Pictures\\some_image.png")) level.save() Using the save() method raise an OSError: OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'C:\\Users\\me\\projects\\media\\level_figures\\C:'. I don't understand why there si a "C:" at the end of my path. Does anyone got the same issue ? -
[Django]How to get the str(id) of a ModelA object in order to give the source code of a page as initial value of a CharField that belongs to a ModelB?
I started to code a two-apps django project. ModelA belongs to appone and ModelB belongs to apptwo. My purpose is to create a ModelA instance everytime that the user creates a ModelB instance. And the value of a ModelA CharField (that is ckeditor widgeted) must be the source code of a ModelB admin view. I used a post_data signal to link a function of creation for that. The problem is that i use the id of each instance of ModelB in order to create the good content for each instance of ModelA. When I try to use a string of the url sending the id parameter, the content field has for value the source code of the debug page (error 500, DoesNotExist at /admin/apptwo/modelb/my_view/ref=76, [76 is an example] ModelB matching query does not exist. Exception location : /home/me/Desktop/env/lib/python3.5/site-packages/django/db/models/query.py in get, line 385) But when I try to visit the url "http://localhost:8000//admin/apptwo/modelb/my_view/ref=76", or when I hardcode the url, without a str(instance.id), the page exists and everything works perfectly. I don't understand why. Could anybody give me some help to solve this problem ? Thanks in advance, PS : The first app has a model.py that contains the following code : from … -
django-cms Custom login page
I am using django-cms as a plugin in my webapp, to create a blog that requires membership (user registration/login). I can't seem to find any examples that show how to do this. I am thinking of proceeding as follows: Using django registration/login Requiring logged in credentials to view specific pages. Is this the correct way of achieving this functionality? -
Serializer for custom User model
I am new to Django 1.9, Rest Framework I have an models.py as follows: class UniservedTeam(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) Role = ArrayField(models.CharField(max_length=1000), blank=True,null=True) ContactNumber = models.CharField(max_length=100) What I have tried is:- from rest_framework import serializers from django.contrib.auth.models import User from models import UniservedTeam class UniservedTeamSerializer(serializers.ModelSerializer): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) Role = ArrayField(models.CharField(max_length=1000), blank=True,null=True) ContactNumber = serializers.CharField(max_length=100) class Meta: model = User fields = ('id', 'username', 'password', 'first_name', 'last_name', 'email', 'city') What serializer's methods I should use for Id and Role fields? How do I write serializer for post and get method? -
django-cms page url extension ending and format
I am new to django-cms. I am creating auxiliary pages that will not necessarily be used in page menus - for example, help, login etc. I am using the slug page attribute, to set the url. However, I notice that django-cms is imposing a url format that is not exactly SEO friendly. For example, I want my help page to have a url like this: mysite.com/help.html however, the url generated by django-cms, is: mysite.com/help/ How may I change this default behaviour, so I can use my own url formatting? -
Is it possible to reload Django application without stopping it?
I have a Django Software as a service (Saas) application with one single postgresql database. When a new User is created, it automatically creates two tables associated to him. A part of the code: def handle(self, *args, **options): Client.objects.create(...attributes...) call_command('makemigrations', interactive=True) call_command('migrate', interactive=True) But when I go the admin site, the new tables are not displayed, I need to stop and restart server. Is there a way to reload it without stopping the service ? -
why my admin url don't work
Traceback (most recent call last): File "C:/Users/daniel/AppData/Local/Programs/Python/Python36-32/final_one/final_one/urls.py", line 23, in <module> url(r"^admin/", admin.site.urls), File "C:\Users\daniel\env_new_1\lib\site-packages\django\contrib\admin\sites.py", line 280, in urls return self.get_urls(), 'admin', self.name File "C:\Users\daniel\env_new_1\lib\site-packages\django\contrib\admin\sites.py", line 238, in get_urls from django.contrib.contenttypes import views as contenttype_views File "C:\Users\daniel\env_new_1\lib\site-packages\django\contrib\contenttypes\views.py", line 5, in <module> from django.contrib.contenttypes.models import ContentType File "C:\Users\daniel\env_new_1\lib\site-packages\django\contrib\contenttypes\models.py", line 139, in <module> class ContentType(models.Model): File "C:\Users\daniel\env_new_1\lib\site-packages\django\contrib\contenttypes\models.py", line 140, in ContentType app_label = models.CharField(max_length=100) File "C:\Users\daniel\env_new_1\lib\site-packages\django\db\models\fields\__init__.py", line 1057, in __init__ super(CharField, self).__init__(*args, **kwargs) File "C:\Users\daniel\env_new_1\lib\site-packages\django\db\models\fields\__init__.py", line 172, in __init__ self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE File "C:\Users\daniel\env_new_1\lib\site-packages\django\conf\__init__.py", line 56, in __getattr__ self._setup(name) File "C:\Users\daniel\env_new_1\lib\site-packages\django\conf\__init__.py", line 39, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_ -
Django-cms page menu not displaying correctly
I have created the following custom menu template for my website: {% load menu_tags %} {% for child in children %} <li class="{% if child.children %}dropdown {% endif %} child{% if child.selected %} selected{% endif %}{% if child.ancestor %} ancestor{% endif %}{% if child.sibling %} sibling{% endif %}{% if child.descendant %} descendant{% endif %}"> <a href="{{ child.attr.redirect_url|default:child.get_absolute_url }}">{{ child.get_menu_title }}</a> {% if child.children %} <ul class="dropdown-menu"> {% show_menu from_level to_level extra_inactive extra_active template "" "" child %} </ul> {% endif %} </li> {% endfor %} I have the following pages that are shown in the menu: Home Page1 Page2 Page3 Page5 Page6 When I go to the home page, the menu is displayed correctly (down caret shown here as 'v'): Home (v) Page1 Page2 Page3 However, when I click on any other page (i.e. Page1,2 or 3), the caret disappears: Home Page1 Page2 Page3 The reason for the caret is to give a visual clue that a menu has child items. I can't seem to find why this is happening. Is there something wrong with my HTML (above?) -
cPickle.dumps of a django model object throws TypeError: can't pickle function objects
I am trying to pickle a django model object in django 1.11 and it is throwing an error - "TypeError: can't pickle function objects" I am using cPickle.dumps(obj) I understand we cannot pickle function objects. But same object when I try to pickle in django 1.3 environment it is doing it properly. So, to check this I went into copy_reg.py -> _reduce_ex function, here self is coming as function my_func_name at 0x7fe5075e6f50 in django 1.11 and django.db.models.base.ModelState object at 0x7fdda59765d0 in django 1.3. So, in django 1.3 ModelState can be pickled but not in django 1.11 as it is function object. Why is the self coming as function in 1.11 and ModelState class in 1.3. -
How do I run tests against a Django data migration?
Using the following example from the documentation: def combine_names(apps, schema_editor): Person = apps.get_model("yourappname", "Person") for person in Person.objects.all(): person.name = "%s %s" % (person.first_name, person.last_name) person.save() class Migration(migrations.Migration): dependencies = [ ('yourappname', '0001_initial'), ] operations = [ migrations.RunPython(combine_names), ] How would I create and run a test against this migration, confirming that the data is migrated correctly? -
Django: Can't import multiply legacy databases
So I am trying to stand up a Django site that will query my DBs and return reports. I have 5 legacy DBs that need to be imported. I set one as default and ran inspectdb. This one imported correctly and now is all set. I ran inspectdb against the next, got the models but when I click on the link in admin panel I get an error. My default db name is app2, and the second db im working with is cucm. There error says that there is no db at app2.cucm - Why is django trying to go to app2.cucm instead of just going to cucm like it should????? -
django prefetch_related and select_related on parent table
I have the following db structure: catogory id name parent_id class Category(models.Model) name = models.CharField(max_length=400, blank=True, null=True) parent = models.ForeignKey("self", blank=True, null=True) I need to fetch all categories and their parent. If I do: Category.objects.select_related("parent").filter(pk__in=[ids]) it would just return the parent of the first level. How can I retrieve the parents of all level with minimum db calls? -
Redirecting API requests in Django Rest Framework
I have a two-layer backend architecture, where the 'front' server occasionally needs to forward request to a 'back' server (which holds top-secret-proprietary-kick-ass-algorithms). I'm using DRF throughout the application. I know I can use requests, but is it possible to simply redirect API requests from the 'front' server to the 'back' server? -
How to extend the process of user activation in django user registration into custom view
I have customer model which contains boolean field email_verified and I have default User model of django. Now when user register with his few details and after submitting registration form we send user with email activation link to his email id. When user clicks that activation link that time User object active status becomes True. At this stage I want to update my customer model field email_verified to True. NOTE: Make sure that I'm using django's default user registration module with its default registration templates. How do I do this without interrupting django's default inbuilt functions inside virtual environment. So that whenever I wants to remove django from my virtual environment and reinstall it again then above functionality should work. Is there anyway of extending this default behaviour of setting User active=True after clicking on activation link into my custom views and update the customer email_verified field to True. -
django put data table in model
(A Django rookie here) For a "project" model I want to store some data. The data is about housing property. So, for example: Number of living spaces, on which floor those spaces are, and how big those spaces are. Living-space 1 - Groundfloor - 50m2 Living-space 2 - First floor - 82m2 etc. Because not every project object has the some amount of living spaces and some project object's also have a row called something like Shop-space or restaurant space I was wondering about a good approach to storing this data. Basically I want to store a dynamically sized table in a model. Below is pretty good example: Restaurant - Groundfloor - 147m2 Livingspace 1 - First floor - 55m2 Livingspace 2 - First floor - 110m2 Livingspace 3 - Second floor - 55m2 Livingspace 4 - Second floor - 110m2 Livingspace 5 - Third floor - 147m2 Now some projects will have only 2 maybe 3 living spaces and no Restaurant's etc. Others will have maybe up to 10 living spaces. I was thinking about creating 10 row fields. So I can put in comma separated values (or maybe JSONfield). Something like: row_01 = models.CharField(max_length=100) row_02 = models.CharField(max_length=100) row_03 … -
Django Rest Framework - IntegrityError: null value in column "user_id" violates not-null constraint
I am new to Django, want to create custom user models as follows: from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.db import models class UniservedTeam(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Role = ArrayField(models.CharField(max_length=1000), blank=True,null=True) ContactNumber = models.CharField(max_length=100) In shell I am trying to create an user : >>> user = User.objects.create(email='piyush@uniserved.com',password='Piyush@123',username='Piyush@24',last_name='Wanare',first_name='Piyush',is_active=True) >>> user <User: Piyush@24> >>> user.id 1 >>> team = UniservedTeam.objects.create(id=user.id,Role=['Vendor Co-ordinator'],ContactNumber='862339798167') Getting Error as follows: Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/models/manager.py", line 122, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/models/query.py", line 401, in create obj.save(force_insert=True, using=self.db) File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/models/base.py", line 700, in save force_update=force_update, update_fields=update_fields) File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/models/base.py", line 728, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/models/base.py", line 812, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/models/base.py", line 851, in _do_insert using=using, raw=raw) File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/models/manager.py", line 122, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/models/query.py", line 1039, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 1060, in execute_sql cursor.execute(sql, params) File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/utils.py", line 95, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/backends/utils.py", … -
How to pass a GET parameter in Django in UTF-8
I want to pass a GET parameter when rendering a view in Django. My code is as follows : class CustomerList(ListView): model = Customer template_name = 'management/customer_list.html' def get(self, request): search_text = request.GET.get('search_text', '') # check if search_text exists query = Q(name__icontains=search_text) | Q(phone_number__icontains=search_text) object_list = self.model.objects.filter(query).order_by('-regdate', '-id') if object_list.count() == 0: response = redirect('management:customer-create') response['Location'] += '?name=%s' % (search_text) return response context = { 'object_list':object_list, 'search_text':search_text, 'count':self.model.objects.count() } return render(request, self.template_name, context) and the resulting url goes like this: /customer/=?utf-8?b?L2N1c3RvbWVyL2NyZWF0ZS8/bmFtZT3tmY3quLjrj5k=?= with page not found error What do you think am I doing wrong? -
django user creation form with auth.user clean method
I make a form to add users in my front-end but the form does not validate duplicated username.I'm using auth.user model. I try override clean method but no success. This is my code: views.py from django.contrib.auth.models import User, Group @login_required(login_url='/login/') @permission_required('auth.add_user',raise_exception=True) def user_new(request): if request.method == "POST": form = NewUserForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.set_password(user.password) user.save() return redirect('userdetail', user.id) else: form = NewUserForm() return render(request, 'ace/user_edit.html', {'form': form}) forms.py class NewUserForm(forms.ModelForm): class Meta: model = User fields = ['username','first_name','last_name','password','email','is_active','is_staff','groups'] widgets = { 'username':TextInput(attrs={'class': u'form-control'}), 'first_name':TextInput(attrs={'class': u'form-control'}), 'last_name':TextInput(attrs={'class': u'form-control'}), 'password':PasswordInput(attrs={'class': u'form-control'}), 'email':EmailInput(attrs={'class': u'form-control'}), 'is_active':NullBooleanSelect(attrs={'class': u'form-control'}), 'is_staff':NullBooleanSelect(attrs={'class': u'form-control'}), 'groups':SelectMultiple(attrs={'class': u'form-control'}), } def clean_username(self): username = self.cleaned_data['username'] user_exists = User.objects.get(username=username) if user_exists: raise ValidationError("User exists") When i create a new user OK, but when a try create a user that same username of other i get a error: The view ace.views.user_new didn't return an HttpResponse object. It returned None instead. If I add a print line "print form.errors" in view i get in console: usernameUser exists But nothing in form.