Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
wat eroor in the code [on hold]
AttributeError at /admin/login/ 'WSGIRequest' object has no attribute 'user' Request Method: GET Request URL: http://127.0.0.1:8000/admin/login/?next=/admin/ Django Version: 1.8 Exception Type: AttributeError Exception Value: 'WSGIRequest' object has no attribute 'user' Exception Location: /usr/local/lib/python2.7/dist-packages/django/contrib/admin/sites.py in has_permission, line 162 Python Executable: /usr/bin/python Python Version: 2.7.11 Python Path: ['/root/Desktop/mysd', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7', '/usr/lib/python2.7/dist-packages/wx-3.0-gtk2'] Server time: -
Django REST: getting serializer model field's default value
Using Django and REST for my project. At some point I need to access serializer model's field default value (since REST doesn't set default values). The code looks like this: # try to get default from model, if it is not set then try to get default from serializer default = serializer.Meta.model._meta.get_field(input_instance.field_name).default I think this is ugly. Is there any way to shorten this exprassion? -
Django: The requested URL was not found on this server
this is list of some of the URLs I am using for a Django project. url(r'^pt_data/$', views.preliminary_data, name='Preliminary Data'), url(r'^pt_test_detail/$', views.pt_test_detail, name='Pt Test Detail'), url(r'^pt_test_testdetail/$', views.pt_test_test_detail, name='Pt Test Detail '), url(r'^pt_test_syllabus/$', views.pt_test_syllabus, name='Pt Test Detail '), # Detail about the syllabus url(r'^test/individual/graph', views.test_individual_graph, name='Test Individual Graph') Except test/individual/graph api, no other url is found on server. I have corresponding functions written in views. I get following error, for reasons unknown. The requested URL /pt_test_syllabus was not found on this server. Someone please tell what am i missing. -
Django view execution order for same url pattern requests?
Let we say two users access the same urls that lead two requests were send to django views. The question is, how does django deal with these two requests? Does them be handled in two different threads simultaneously or when one end it request-middleware-response life cycle then the other be handled? -
Uploading images use Django Ckeditor --getting server error(500)
Uploading images use Django Ckeditor --getting server error(500) I have been struggling for the problem for two days. Unfortunately, i still have no idea to solve it due to my poor knowledge. So i have to come here to ask for help. Very appreciate ! I want to write a website as a my blog and use Django to implement it. To develop this website, i have to use rich text editor, so i use CKeditor on admin panel. Here is the link of Ckeditor source code on github. https://github.com/django-ckeditor/django-ckeditor To upload images using ckeditor widget , i edit ../static/ckeditor/ckeditor/plugins/image/di alogs/image.js so can display the images upload button. id:"Upload",hidden:!0 I also add upload url in config.js. After that, i set routing in the urls.py and add a view function in views.py. Everything was ok on my computer, but when i deploy it to website server i getting server error(500). Ckeditor widget can not return the urls but i can find the images on server which i uploaded by ckeditor. $:~/sites/www/source$ ls ../media/images/ 20161219045646_7.jpeg 20161219053949_0094.jpg $:~/sites/www/source$ config.js (the locationstatic/ckeditor/ckeditor/) /** * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.editorConfig … -
djoser django activate api return error user not found
i make registration in my app with djoser : https://github.com/sunscrapers/djoser the register + me+ login apis work great but the activate api returns error user not found or not exist. but the /me api returns the correct user and im sending the uid and token to activate it andd it return error "uid": [ "Invalid user id or user doesn't exist." ] any ideas why? thanks -
Django shibboleth attribute-map settings
I am building django application where user is authenticated using django-shibboleth-remoteuser. What i have done so far. settings.py INSTALLED_APPS += ( ‘myapp’, 'shibboleth', ) Default provided at django-shibboleth-remoteuser SHIBBOLETH_ATTRIBUTE_MAP = { "shib-user": (True, "username"), "shib-given-name": (True, "first_name"), "shib-sn": (True, "last_name"), "shib-mail": (True, "email"), } Modified SHIBBOLETH_ATTRIBUTE_MAP = { "shib-user": (True, "uid"), "shib-given-name": (True, "displayName"), "shib-sn": (True, "sn"), "shib-mail": (True, "email"), } In wsgi request meta information I can see (uid, title, sn, mail, id, displayName) attributes delivered by the apache server. With both above settings i get ShibbolethValidationError If I change SHIBBOLETH_ATTRIBUTE_MAP to False then it doens't complain about ShibbolethValidationError So my question is how can I map custom shibboleth meta-attributes in the django settings? -
How to refactor duplicate method inside class based views for Django 1.9
I have a class based view called PalletContentProductionView @method_decorator(PermissionManager.production_worker_required, name='dispatch') class PalletContentProductionView(APIView): """ Update a Pallet Content count and/or product """ def put(self, request, pk): pallet_content = QuickFind.get_pallet_content_or_404(pallet_content_id=pk) def validate_pending_and_created_by_user(pallet_content, user=request.user): if not pallet_content.pending(): raise PermissionDenied("Non-Pending pallet content cannot be updated by production worker") EntryFormHelper.throw_403_when_not_created_by_user(pallet_content=pallet_content, user=user) return update_pallet_content(request, pallet_content, validate_pending_and_created_by_user) """ Delete pallet only if pallet content is pending and creater by user """ def delete(self, request, pk): pallet_content = QuickFind.get_pallet_content_or_404(pallet_content_id=pk) def validate_pending_and_created_by_user(pallet_content, user=request.user): if pallet_content.pending() is False: raise PermissionDenied("Non-Pending pallet content cannot be updated by production worker") EntryFormHelper.throw_403_when_not_created_by_user(pallet_content=pallet_content, user=user) return delete_pallet_content(request, pallet_content, validate_pending_and_created_by_user) I was wondering how do I refactor such that the four lines of duplication can be avoided? The four lines are : def validate_pending_and_created_by_user(pallet_content, user=request.user): if not pallet_content.pending(): raise PermissionDenied("Non-Pending pallet content cannot be updated by production worker") EntryFormHelper.throw_403_when_not_created_by_user(pallet_content=pallet_content, user=user) I have tried to pull it out and make it inside the PalletContentProductionView and adjacent to the put and delete methods but it was wrong. -
Django forms integerfield and emailfield represents what type?
I'm having some issues changing Djang Form's CSS. Here is my code (Template): <form method="post" action="." id="signup"> <div class="container"> {% csrf_token %} {{ form.as_p }} <button type="submit" value="{% trans 'Submit' %}">Join Hawka</button> </div> </form> Model: class ExRegistrationForm(RegistrationForm): age = forms.IntegerField() location = forms.CharField() phone = forms.CharField() Model: class ExUserProfile(models.Model): user = models.ForeignKey(User, unique=True) age = models.PositiveSmallIntegerField(default = 19) location = models.CharField(max_length=2, default = "location") phone = models.CharField(max_length=15, default = "phone number") def __unicode__(self): return self.user def user_registered_callback(sender, user, request, **kwargs): profile = ExUserProfile(user = user) profile.age = request.POST["age"] profile.location = request.POST["location"] profile.phone = request.POST["phone"] profile.save() CSS: .container input[type=text], .container input[type=password], .container input[type=email], .container input[type=number] { width: 100%; padding: 0.3em 0.5em; margin: 0.3em 0; font-size: 1.5em; text-align: center; display: inline-block; border: 0.1em solid #ccc; box-sizing: border-box; border-radius: 1em; } Result: The style for email and age is different, I assume because the input type is different and I haven't properly setup the a CSS for it. I have setup css for input type "number" and "email", but it isn't working. What am I doing wrong? -
when i'm using (from django.conf.urls (or) .defaults import patterns, url ) or it will provide can't import name 'patterns'
from django.conf.urls import patterns, url from django.views.generic import TemplateView urlpatterns = patterns('melting.views', url(r'^connection/',TemplateView.as_view(template_name = 'home_page.html')), url(r'^login/', 'login', name = 'login')) -
NoReversMatch for url with parameter
So i have a simple model and i want to display list of my recipes. So in urls.py i have following url: urlpatterns = [ url( regex=r'^$', view=views.RecipeListView.as_view(), name='list' ), url( regex=r'^(?P<name>[\w.@+-]+)/$', view=views.RecipeDetailView.as_view(), name='detail' ), ] name is just a name of recipe it can be anything. And than at my list i have following to give url: <div class="list-group"> {% for recipe in recipe_list %} <a href="{% url 'recipes:detail' recipe.name %}" class="list-group-item"> <h4 class="list-group-item-heading">{{ recipe.name }}</h4> </a> {% endfor %} </div> so i am passing argument of name into detail view but i still get error NoReverseMatch at /recipes/ Reverse for 'detail' with arguments '(u'This is my test recipe',)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'recipes/(?P[0-9A-Za-z._%+-]+)/$'] And i am not sure what i am doing wrong. -
Why choice.set is used instead if Choice.set?
i am learning django from documentation. Following is the models.py from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) this is executed in the shell q = Question.objects.get(pk=1) q.choice_set.all() Here why q.choice_set is used instead of q.Choice_set? Is choice_set some inbuilt function or it is used because of Choice in models.py, if so why its first letter is taken in small case Thank you in advance -
Django-Celery Periodic tasks error handling
I am an amateur coder. My problem is I have a Celery task that runs periodically in background. The tasks takes no argument. Now i want to use on_failure to traceback on the error for the particular object in encounters. Since it doesnt takes any argument I am not able to assign the value to args. How should I get the object and the error it encounters while the task is getting executed -
How to get right file path from "../../" and another path with python
I am doing content linking check on user's upload zip file with Python's zipfile and BeautifulSoup module. In the zip file, there is a file "a.html" and its full path in the zip file is "content/product1/component1/a.html". File 'a.html' has a <a href="../../product2/component2/b.html"> link to another HTML file. I want to know how to combine the path "content/product1/component1/a.html" with "../../product2/component2/b.html" and get the right path which is "content/product2/component2/b.html". So I can check where this file exists. I tried os.path.join("content/product1/component1/a.html","../../product2/component2/b.html), but I don't get "content/product2/component2/b.html". Does anyone know how to do that? -
Django: two forms in one view
How would I write a view with a form to add a new person, and on the same form, be able to add 0 or 1 or 2 or ... 68757857 images of that person? Please refer to the code below. What I have in models.py: class Person(models.Model): name = models.CharField(max_length=50) class Image(models.Model): person = models.ForeignKey(Person) image = models.ImageField(upload_to='images/') And in forms.py: class PersonForm(forms.ModelForm): class Meta: model = Product fields = ['name'] class ImageForm(forms.ModelForm): class Meta: model = Image fields = ['person', 'image'] From what I have seen, formsets are used. I have looked at many examples on SO, read the documentations and I am still confused. I would appreciate it if someone can provide an example of a views.py that fulfils the specification at the beginning of this question. -
ImportError: No module named functions in django
I am not able to access functions.How can I add functions in my model? Thanks in advance! from django.db.models.functions import TruncMonth ImportError: No module named functions report.objects.filter(r_id=id, r_checkin_date__gte=checkin_date) .annotate(month=ExtractMonth('timestamp')) .values('month') .annotate(count=Count('id')) .values('month', 'count') -
Django Rest Framework Bulk - Update or Create
I had a question about Django Rest Framework Bulk. Specifically, I want to know if DRF Bulk can support batch Create or Update. The code seems to suggest that they need to be done independently - only creates happen with the BulkCreateModelMixin and only updates happen with the BulkUpdateModelMixin. Is this correct - is there no way to have both new objects and updates happen via the same view/serializer? DRF Bulk Mixins DRF Bulk Serializers -
Django JSONField querying
I want to use Django's JSONField for custom permission system. But I can't find how to query it in my case. The thing I'm doing looks (roughly) like this: class MyObject(models.Model): permissions = model.JSONField(default=dict) Permissions structure is like: { group_id: [perm_codename, perm_codename, perm_codename...], group_id: [perm_codename, perm_codename, perm_codename...], ... } How do I select objects, which has group_id=5 and its list of permissions (perm_codenames) contain 'CAN_READ' and 'CAN_WRITE'? -
Django: Section links to answers
Hi I am developing a Django forum application. I am stuck at one place, how to generate links for replies to the forum post. A link like this: domain.com/post-title-1/#r1 Where clicking on it will take you to the reply one and same for other replies. Thank you. -
Prompt File Download after upload in django admin
I have a django admin Page where user is uploading a file, the data is read in-memory, without actually storing the file. Based on the content, a new file is generated on the disk.All thsi happend in clean method before the save_model is called out. def clean(self): obj = Parser() cleaned_data = super(MyMethodAdminForm, self).clean() input_data = self.request.FILES['file_name'].read().split('\n') base_file = settings.MEDIA_ROOT + "/uploads/" + cleaned_data.get('file_name').name # This is the output file, which needs to be downloaded output_filename = base_file.replace('.csv', '_output.csv') output_list = [] # Read the file and prepare the output data # on the basis of the input data for line in input_data: data = line.split(",") if len(data) > 1: dt = obj.get_data() current_list = [data[0], data[1]] else: dt = obj.get_data() current_list = [data[0]] current_list.append(str(dt)) output_list.append(current_list) # Prepare the file on the basis of the output data with open(output_filename, 'a') as outcsv: # configure writer to write standard csv file writer = csv.writer(outcsv, delimiter=',', quotechar=' ', quoting=csv.QUOTE_MINIMAL, lineterminator='\n') for item in output_list: if len(item) > 2: # Write item to outcsv writer.writerow([item[0], item[1], item[2]]) else: writer.writerow([item[0], item[1]]) return cleaned_data Now, my problem is that i have to allow for this file download, but since, the upload domain is handled through … -
How to print model properties to excel?
I want to export my table into the csv file . But some of the fields in my table are properties. For example those: 'current_tobe_payed', 'current_balance', 'current_period','total_payment', 'total_discount' def export_leaseterm_csv(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="leaseterm.csv"' writer = csv.writer(response) writer.writerow(['start_period', 'end_period', 'lease', 'increase', 'amount', 'is_terminated', 'current_tobe_payed', 'current_balance', 'current_period','total_payment', 'total_discount']) leaseterms = LeaseTerm.objects.all().values_list('start_period', 'end_period', 'lease', 'increase', 'amount', 'is_terminated', 'current_tobe_payed', 'current_balance', 'current_period','total_payment', 'total_discount') for leaseterm in leaseterms: writer.writerow(leaseterm) return response I am getting Cannot resolve keyword 'current_tobe_payed' into field. How Can I overcome it? -
replace the #blank# line so that the code prints "even" if n is even, and "odd" if n is odd?
Can you replace the #blank# line so that the code prints "even" if n is even, and "odd" if n is odd? if n%2 == 0: #blank# else: print("odd") -
Django shell inside Emacs showing escape characters
I'm having trouble using the manage.py shell inside Emacs. I get something like this: Python 3.4.3 (default, Nov 17 2016, 01:08:31) Type "copyright", "credits" or "license" for more information. IPython 5.1.0 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object', use 'object??' for extra details. [J[?7h[?12l[?25h[?2004l [?12l[?25h And every time I press enter I get these escape character in the beginning of the line. The terminal actually still works, but it is very unpleasant. I think it is an encoding error of some kind, but I have no idea how to fix it. I'm using Emacs 24.3.1, and use the django-python package to run the shell inside Emacs. I'm kind of a newbie to all this, sorry if the question is not properly put. Thanks -
Reverse for 'password_change_done' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
I am getting the following error in Django. Reverse for 'password_change_done' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []. I am not really sure why i am getting this error. urls.py from django.conf.urls import url from django.contrib.auth import views as auth_views from . import views urlpatterns = [ url(r'^login/$', auth_views.login, name='login'), url(r'^logout/$', auth_views.logout, name='logout'), url(r'^logout-then-login/$', auth_views.logout_then_login, name="logout_then_login"), url(r'^$', views.dashboard, name='dashboard'), #change password urls url(r'^password-change/$', auth_views.password_change, name='password_change'), url(r'^password-change/done/$', auth_views.password_change_done, name='password_change_done'), ] Traceback: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/account/password-change/ Django Version: 1.10.4 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'whitenoise', 'crispy_forms', 'business', 'account'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/Users/Tommy/Desktop/django/directory/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/Users/Tommy/Desktop/django/directory/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Users/Tommy/Desktop/django/directory/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/Tommy/Desktop/django/directory/lib/python3.5/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper 76. return view(request, *args, **kwargs) File "/Users/Tommy/Desktop/django/directory/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/Users/Tommy/Desktop/django/directory/lib/python3.5/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "/Users/Tommy/Desktop/django/directory/lib/python3.5/site-packages/django/contrib/auth/views.py" in inner 47. return func(*args, **kwargs) File "/Users/Tommy/Desktop/django/directory/lib/python3.5/site-packages/django/contrib/auth/views.py" in password_change 308. post_change_redirect = reverse('password_change_done') File "/Users/Tommy/Desktop/django/directory/lib/python3.5/site-packages/django/urls/base.py" in reverse 91. return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))) File "/Users/Tommy/Desktop/django/directory/lib/python3.5/site-packages/django/urls/resolvers.py" in _reverse_with_prefix 392. (lookup_view_s, args, kwargs, … -
django multiwidget decompress value is None
I am subclassing Django's MultiWidget class and running into an issue in the decompress method. The decompress method is being called, however 'value' is always None even though there is definitely data in the database for this field. I even tried overriding the render method and value is None here as well. The issue is that value should be non-Null when decompress is called, but instead it is None. I am using MultiWidget in conjunction with a subclass of MultiValueField. Here is the code: forms.py: class MyMultiWidget(forms.widgets.MultiWidget): def __init__(self, attrs=None): self.attrs = attrs widgets = ( TextInput(), TextInput(), CheckboxInput(attrs={'value': False}), CheckboxInput(attrs={'value': False}), CheckboxInput(attrs={'value': False}), CheckboxInput(attrs={'value': False}), CheckboxInput(attrs={'value': False}), CheckboxInput(attrs={'value': False}), CheckboxInput(attrs={'value': False}), CheckboxInput(attrs={'value': False}), CheckboxInput(attrs={'value': False}), ) super(MyMultiWidget, self).__init__(widgets, attrs) def decompress(self, value): # decompress stored database format to HTML form format print('decompress called') print("this is my value: " + str(value)) if value: dict_value = json.loads(value) return dict_value return "" #=============================================================== class MyMultiField(forms.fields.MultiValueField): widget = MyMultiWidget def __init__(self, *args, **kwargs): fields = ( forms.CharField(), forms.CharField(), forms.BooleanField(), forms.BooleanField(), forms.BooleanField(), forms.BooleanField(), forms.BooleanField(), forms.BooleanField(), forms.BooleanField(), forms.BooleanField(), forms.BooleanField(), ) super(MyMultiField, self).__init__(fields=fields, *args, **kwargs) def compress(self, values): print('my values: ' + str(values)) return json.dumps(values) #=============================================================== class MyForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.form_tag …