Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Transform a locale-aware unicode string in a valid Decimal number in Python/Django
In my Django 1.7.11 app, I get data formatted with a spanish locale via HTTP. So, in my view, I get a unicode string representing a decimal number in spanish locale: spanish_number = request.GET.get('some_post_value', 0) # spanish_number may be u'12,542' now, for example. And may come via POST. This is not important. Just the value itself is important: it contains commas as decimal separator. And I want to store that in a Django Model's field of type DecimalField: class MyModel(models.Model): my_number = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True) In my settings.py, I have USE_L10N=True USE_I18N=True If I try something like m = MyModel() m.my_number = spanish_number # This is, u'12,542' m.save() It fails with a ValidationError because u'12,542' must be a decimal number What would be the right way to deal with this? I mean, with the fact that my application is going to receive numbers (and dates...) formatted this way (spanish locale) P.S.: I know Django has a DecimalField for forms, with a localize=True option, but I'm directly dealing with Models, not with Forms. -
How to get model instance's attribute in UpdateView (Django)?
I have an UpdateView for a model. I want to get the 'car_owner' attribute (of the Newcars model) in the UpdateView. Here's the code. models.py class Newcars(models.Model): shop_no = models.ForeignKey(Shop, on_delete=models.CASCADE, default=0, related_name='newcars') car_name = models.CharField(max_length=250) car_owner = models.CharField(max_length=250) def get_absolute_url(self): return reverse('carapp:index') def __str__(self): return self.car_name + ' - ' + self.car_owner views.py (Here's the UpdateView.) class NewcarUpdate(UpdateView): model = Newcars fields = ['car_name', 'car_owner'] urls.py (only the necessary part of the urlpatterns) url(r'^newcars/(?P<pk>[0-9]+)/$', views.NewcarUpdate.as_view(), name='newcar-update'), This is what I intend to do with the UpdateView, but cannot understand how. class NewcarUpdate(UpdateView): model = Newcars fields = ['car_name', 'car_owner'] #Get the selected newcar object's 'car_owner' attribute. #Check if the object's 'car_owner' attribute == "sometext" or not. #If matches, only then go the normal update form. #If doesn't, redirect to a 404 page. -
Django- UpdateView - Different types of models
how can I change model in UpdateView for different type of users? I have staff and student inherited from CustomUser, and I need edit for for them class EditUser(UpdateView): success_url = '/' template_name = 'editprofile.html' model = staff (I need to choose this Staff or Student) How do i do it? Im new to django. I'll appreciate if you provide me with an example. Thank you. -
DRF cant send request - missing 1 required positional argument
I try to make a view, which saves file from request and creates object in db. My code is following class ProfileCreateAPIView(CreateAPIView): queryset = Profile.objects.all() serializer_class = ProfileCreateSerializer permission_classes = (IsAuthenticated,) parser_classes = (MultiPartParser, FormParser,) def perform_create(self, serializer, request): upload = self.request.FILES['file'] fh = tempfile.NamedTemporaryFile(delete=False) extension = upload.name.split(".")[1] filename = "{}.{}".format(fh.name,extension) with BufferedWriter( FileIO( filename, "w" ) ) as dest: for c in upload.chunks(): dest.write(c) now = datetime.datetime.now().strftime(UPLOAD_TITLE_NAME) serializer.save(user=self.request.user, url="http://example.com/uploads/{name}".format( name=filename.split("/")[2]), path_to_image=filename) return Response({}, status=201) When I try to send data here, I get an error of perform_create() missing 1 required positional argument: &#39;request&#39; What am I doing wrong ? -
NoReverseMatch at /courses/course/1/1/
I was editing the template to include a hyperlink. But when I do I get NoReverseMatch error. Reverse for 'views.hello_world' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] The template file: layout.html {% load static from staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" href="{% static 'css/layout.css' %}"> </head> <body> <div class="site-container"> <nav> <a href="{% url 'views.hello_world' %}">Home</a> [**Error here**] </nav> {% block content %}{% endblock %} </div> </body> </html> urls.py from django.conf.urls import include, url from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from . import views urlpatterns = [ url(r'^courses/', include('courses.urls')), url(r'^admin/', admin.site.urls), url(r'^$', views.hello_world) ] urlpatterns+=staticfiles_urlpatterns() views.py from django.shortcuts import render def hello_world(request): return render(request, 'home.html') The line, Home when removed I don't get any error. But I add, the NoReverseMatch arises. What am I doing wrong? -
dynamic path for saving files not generating correct URL (django)
I have two models that should save images with their forms. Unfortunately, these aren't being saved to the upload location. Can anyone see why? models.py class UserProfile(models.Model): user = models.OneToOneField(User) ... picture = models.ImageField(upload_to=upload_location, blank=True) def __unicode__(self): return self.user.username class Offer(models.Model): name = models.CharField(max_length=120) maker = models.ForeignKey(UserProfile) icon = models.ImageField(upload_to=upload_location, null=True) def __unicode__(self): return self.name I define the upload_location dynamically: def upload_location(self, filename): try: user = self.user.id url = "images/profile_pictures/%d/%s" % (self.user.id, filename) except AttributeError: url = "images/offer_icons/%d/%s" % (self.maker.id, filename) return url My media path looks like: media/images/profile_pictures. offer_icons. .. The views that save these do the following: def register(request): registered = False if request.method == "POST": user_form = UserForm(request.POST) profile_form = UserProfileForm(request.POST, request.FILES) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user profile.save() else: print user_form.errors, profile_form.errors else: profile_form = UserProfileForm() user_form = UserForm() return render(request, "register.html", {'user_form' : user_form, 'profile_form' : profile_form}) If the view for saving the offer is necessary to include, someone can ask for it, but the issue is probably the same as for the profile. My HTML does include "enctype="multipart/form-data" with the form. -
Running blockchain-wallet-service on a Heroku worker
I'm trying to deploy my Django app on Heroku, that makes use of the Blockchain.info API V2 (https://github.com/blockchain/service-my-wallet-v3) and thus needs to run blockchain-wallet-service in the background, which in turn needs Node.js and npm installed. On localhost, I have used this API successfully by running the service on my own machine, but I'm having trouble deploying to Heroku. Firstly, I assume I will need to run the service on a separate dyno, and that I will need node and npm installed on my instance. Can someone tell me how to achieve this? I'm new to more advanced features of Heroku, I've tried to use the nodejs buildpack but I doubt this is the correct way. There is also this: https://elements.heroku.com/buttons/kmhouk/service-my-wallet-v3 which I've deployed as a separate app but I've failed to merge it in some way to my Django app. Any help is much appreciated! -
What is the best way to create service using python?
I have a droplet running Ubuntu 14.04 on digital ocean, using nginx, gunicorn and django to run the web site, and I would like to create a separate program (a service perhaps?) to perform some pretty intense mathematical operations (requiring the use of numpy in python) and return the results to the django app. I cannot use the code in the django app to perform the calculations because it would require loading a large amount of data into RAM for each request. The data to be computed is the same for all website visitors so it would not make sense to keep destroying and loading the data for each user. I would like to be able to create a totally separate service using python, load all of my variables into RAM inside that service, and have the Django code connect to that service, ask it to perform some calculation, and return the result to the user. I know that no one can give me a complete recipe for this in one answer, but a pointer in the general direction would be a great help. -
when trying to run celery local I get an error message
This is my file structure venv/ src/ blog/ __init__.py admin.py forms.py models.py tasks.py urls.py views.py my views.py from .tasks import add, p_panties def shopan(request): # one = scrape_and_store_world() # two = panties() # argument_scrapes(one, two) p_panties.delay() return redirect('/') my tasks.py import requests import random import re import os from celery import Celery from bs4 import BeautifulSoup app = Celery('tasks', backend='redis://localhost', broker='redis://localhost') @app.task def add(x, y): return x + y @app.task def reverse(string): return string[::-1] @app.task def p_panties(): def swappo(): user_one = ' "Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0" ' user_two = ' "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5)" ' user_thr = ' "Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko" ' user_for = ' "Mozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:10.0) Gecko/20100101 Firefox/10.0" ' agent_list = [user_one, user_two, user_thr, user_for] a = random.choice(agent_list) return a headers = { "user-agent": swappo(), "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "accept-charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3", "accept-encoding": "gzip,deflate,sdch", "accept-language": "en-US,en;q=0.8", } pan_url = 'http://www.example.com' shtml = requests.get(pan_url, headers=headers) soup = BeautifulSoup(shtml.text, 'html5lib') video_row = soup.find_all('div', {'class': 'post-start'}) name = 'pan videos' def youtube_link(url): youtube_page = requests.get(url, headers=headers) soupdata = BeautifulSoup(youtube_page.text, 'html5lib') video_row = soupdata.find_all('p')[0] entries = [{'text': div, } for div in video_row] tubby = str(entries[0]['text']) urls = … -
Django: How to put existing fields when displaying form for UpdateView?
I'm making an episode tracker website and when I want the user to edit a show, the form provided starts with empty fields. How do I fill the form with already existing fields? For example, when a user is watching a show and is originally at episode 5, how do I call the update form with the Episode field already at 5 instead of it being empty? views.py class ShowUpdate(UpdateView): model = Show slug_field = 'title' slug_url_kwarg = 'show' fields = ['description', 'season', 'episode'] show-detail.html <form action="{% url 'show:show-update' show=show.title %}" method="post"> {% csrf_token %} <button type="submit">Edit</button> </form> -
How in django can i insert list view within detail view using mixins
I want to override get_context_data with containing data from other model. I have Detail View, and on that website page i want to display list with pagination. -
django template fragment cache not working
I am working on a Django 1.10.1 site and attempting to use fragment caching. However I am not seeing any cache sets or hits in memcached which is the configured backend. If I set a full view cache it caches fine into memcache. Example: {% load cache %} ... some html ... {% cache 600 content %} ... some html and template tags ... {% end cache %} The only change to settings for caching I have made is to setup the backend. CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', }, } -
'python: realpath couldn't resolve' after forced reload
I'v been developing a Django project for few weeks until once my Mac hung, so I reloaded it After I launch terminal and write what always worked for me cd djangoboy source denv/bin/ativate I get this error after whatever command I write after: python: realpath couldn't resolve "/Library/Frameworks/Python.framework/Versions/3.5/bin/python" What could it be? -
AWS Elastic Beanstalk - error requirements.txt
When I try to deploy my Amazon Web Services Elastic Beanstalk project (Python + Django), I get the following error: 2016-09-14 14:46:37,244 ERROR Error installing dependencies: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1 Traceback (most recent call last): File "/opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py", line 22, in main install_dependencies() File "/opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py", line 18, in install_dependencies check_call('%s install -r %s' % (os.path.join(APP_VIRTUAL_ENV, 'bin', 'pip'), requirements_file), shell=True) File "/usr/lib64/python2.7/subprocess.py", line 540, in check_call raise CalledProcessError(retcode, cmd) CalledProcessError: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1 (Executor::NonZeroExitStatus) I had this error a few months ago and I simply changed my configuration in .ebextensions which enabled the deployment to work correctly (problem was postgresql93-devel missing): packages: yum: git: [] postgresql93-devel: [] libffi-devel: [] I guess AWS has an issue with one or more of my libraries in requirements.txt- I tried installing/deinstalling some of them to find the one that causes the troubles, but haven't managed yet. This is my requirements.txt: awsebcli==3.7.7 beautifulsoup4==4.4.1 boto==2.40.0 botocore==1.4.40 cement==2.8.2 cffi==1.5.2 colorama==0.3.7 cryptography==1.3.1 Django==1.9.4 django-storages==1.4.1 docker-py==1.7.2 dockerpty==0.4.1 docopt==0.6.2 docutils==0.12 enum34==1.1.2 future==0.15.2 futures==3.0.5 gax-google-logging-v2==0.8.1 gax-google-pubsub-v1==0.8.1 google-api-python-client==1.5.0 google-gax==0.13.0 googleads==3.13.0 googleapis-common-protos==1.3.4 grpc-google-logging-v2==0.8.1 grpc-google-pubsub-v1==0.8.1 grpcio==1.0.0 httplib2==0.9.2 idna==2.1 ipaddress==1.0.16 jmespath==0.9.0 oauth2client==2.0.1 pathspec==0.3.4 ply==3.8 protobuf==3.0.0 psycopg2==2.6.1 pyasn1==0.1.9 pyasn1-modules==0.0.8 pycparser==2.14 pyOpenSSL==16.0.0 PySocks==1.5.6 python-dateutil==2.5.3 pytz==2016.2 PyYAML==3.11 … -
Django tests for sending email
I need to test that mail is sent from a Django 1.8 application; the documentation is clear on how to do this, e.g. https://docs.djangoproject.com/en/dev/topics/testing/tools/#email-services Here's some code which should therefore suffice: from myapp.utils.mailutils import mail as mymail from django.core import mail def testThisFails(self): user = User.objects.filter(id=1).__getitem__(0) mymail(user,'Test Message','Test message content, please ignore...') self.assertEquals(len(mail.outbox), 1) self.assertEquals(mail.outbox[0].subject, 'Test Message') ...obviously, I have proper tests as well. Anyway, I get nothing but this: self.assertEquals(len(mail.outbox), 1) AssertionError: 0 != 1 Here's a similar question mentioning that the locmail backend needs to be used: Django 1.3: Outbox empty during tests So, I added this to settings.py: TESTING = len(sys.argv) > 1 and sys.argv[1] == 'test' if TESTING: EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend' ...with no luck. Even omitting the if TESTING doesn't address the issue. Is there any means by which I can get my tests to use this backend directly? -
Django - Having two views in same url
I am making a website in django and in my homepage I want to show the list of my recent blog post and a few blocks below I want to make a simple contact form. The blog and the contact form separately are working fine. But I want to include them in the same page(obviously in the same url). The views.py is: from .forms import NameForm def get_name(request): if request.method == 'POST': form = NameForm(request.POST) if form.is_valid(): return HttpResponseRedirect('/thanks/') else: form = NameForm() return render(request, 'personal/index.html', {'form': form}) If you want to look at the forms.py then : from django import forms class NameForm(forms.Form): your_name = forms.CharField(label='Your name', max_length=100) The urlpattern in urls.py of my homepage is: urlpatterns = [ url(r'^$', ListView.as_view( queryset=Post.objects.all().order_by("-date")[:2], template_name="personal/index.html")), url(r'^$', views.get_name, name='contact'), ] With this urlpatter the list of blog post shows up perfectly but the contact form doesn't show up. But with the below urlpattern contact form shows up but blog posts doesn't show up. urlpatterns = [ url(r'^$', views.get_name, name='contact'), url(r'^$', ListView.as_view( queryset=Post.objects.all().order_by("-date")[:2], template_name="personal/index.html")), ] I want to make both of these contents show up in the same page. Please help me. If you need any more information then do tell. -
Json data not reaching Django properly
In my project, the frontend is in Angular2, I'm making a POST request to a Django url like this: let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); let body = JSON.stringify(this.myMetadata); let req = this.http.post(this.url,body,options) .map((res:Response) => res.json()) .subscribe( data => { this.response = data}, err => console.error(err), () => console.log('done') ); return req; But the Django backend is not receving the data as JSON if request.method == 'POST': logger.info(request.method) logger.info(type(request.body)) logger.info(request.POST) log dumps show that Django has received the data as string, due to this none of the json methods work on it. Method:POST request.body type:<type 'str'> What is the best way to resolve this? is there a way to convert a string to a dictionary? -
In Django, how can I link a static file from within an extended HTML template?
I haven't found anything in the Django Docs or any Stack Overflow solutions to this same problem. Say I have a html file like the following: {% extends 'base.html' %} {% block cssfile %} <!-- css link goes here --> {% endblock %} {% block maincontent %} Hello World {% endblock %} which will of course link to base.html. However, I want to put a css file between the 'block cssfile' tags, but given the way that Django is structured for linking static files, it prevents me from doing this. Something like {% block cssfile %} <link rel="stylesheet"type="text/css"href="{% static 'myappname/css/style.css' %}"/> {% endblock %} will give me this error TemplateSyntaxError at /myapp/1/ Invalid block tag on line 3: 'static', expected 'endblock'. Did you forget to register or load this tag? I've also tried replacing the '{% %}' tags for the href with something like '{{ }}' for example. Any help would be great, thank you. -
unexpected kawrgs ,TypeError at /courses/course/1/1/
I'm getting type error for the pk. Something like: step_detail() got an unexpected keyword argument 'pk' for the second one in /courses/course/1/1, where as it has been taken care in the following method of step_detail. What am I doing wrong? views.py from django.shortcuts import render from django.shortcuts import get_object_or_404 from .models import Course, Step def course_list(request): courses = Course.objects.all() return render(request, 'courses/course_list.html', {'courses': courses}) def course_detail(request, pk): # course=Course.objects.get(pk=pk) course = get_object_or_404(Course, pk=pk) return render(request, 'courses/course_detail.html', {'course': course}) def step_detail(request, course_pk, step_pk): step = get_object_or_404(Step, course_id=course_pk, pk=step_pk) return render(request, 'courses/step_detail.html', {'step': step}) And the url.py: from django.conf.urls import url from . import views urlpatterns= [ url(r'^$', views.course_list), url(r'(?P<course_pk>\d+)/(?P<pk>\d+)/$', views.step_detail), url(r'(?P<pk>\d+)/$', views.course_detail), ] -
Django authentication with DRF and AngularJS
I posted a question on SO that had various questions regarding the confusion that I have on this particular matter. I was told that I should break down my questions into little pieces since my question was too broad, so here I go. I have a backend ready with a lot of views, models and serializers from DRF. Now I want to apply authentication to my app and create RESTful apis that are consumed at the front-end. So the doubts that I have- How does token system works? How does a token sent from the front-end validates at the back-end, when each time a user logs-out and logs back in, a new token is sent? (i.e. How does backend knows the token at the front-end has changed and what to verify it against) How to use token authentication with drf and angularjs? I hope my questions are clear. In case they are not, suggest me edits. I'd also like some examples(if any) on how does this all happens. Also, if you want to see the original post. -
'UserForm' object has no attribute 'get'
I'm working on a django 1.10 project and i am trying to create a view to register new users. Here is my view : class UserFormView(View): form_class = UserForm template_name = 'utilisateur/registration.html' # /Build in fonction for get request/ # /Display a blank form/ def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) # /Build in fonction for post request/ # /Process form data/ def post(self, request): form = self.form_class(request.POST) # /Check validity of data given/ if form.is_valid(): # /Create the object user for the form/ user = form.save(commit=False) # /Normalize data/ username = form.cleaned_data['username'] password = form.cleaned_data['password'] # /Editable password/ user.set_password(password) user.save() # /Check if these data already exist in de db/ user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) # Here you can request something you'd show # About the user e.g: photo etc.. # /Redirect to home page/ return redirect('utilisateur:index') # /Blank form if user not exist/ return render(request, self.template_name, {'form': form}) Here is my url file: # /RegisterPage/ url(r'register', views.UserFormView.as_view(), name='register'), Here is my forms file: class UserForm(forms.ModelForm): password = forms.CharField(label="Mot de passe", widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'email', 'password'] The problem is, when on … -
Django simple model method error (unsupported operand type(s))
Hi I'm trying a simple thing, very documented, working in shell but not working in django admin. my model: class Book(models.Model): name = models.CharField(max_length=30) loan_start = models.DateField() loan_ends = models.DateField() def loan_length(self): temp1 = self.loan_start temp2 = self.loan_ends res = temp2-temp1 return res.days my admin: class BookAdmin(admin.ModelAdmin): list_display = ('name', 'loan_start’, ‘loan_length’, ‘loan_ends’) If I try this method in django shell works perfect: manage.py shell from books.models import * grab some book: somebook = Book.objects.get(id=19) somebook.loan_start Out[12]: datetime.date(2016, 4, 28) somebook.loan_ends Out[13]: datetime.date(2016, 8, 1) somebook.loan_length() Out[3]: 95 But if I try to use it in admin I get this error: Exception Value: unsupported operand type(s) for -: 'NoneType' and 'datetime.date' I'm subtracting one date to another, getting a timedelta and returning it. I really don't know why the exception error. Thanks -
how to extract data from model into csv file (in django)
i have a model with different fields in my Django project I want to extract these data into csv file to save in my computer ((I want to do it by using Django shell)) -
simplest way to override Django admin inline to request formfield_for_dbfield for each instance
I would like to provide different widgets to input form fields for the same type of model field in a Django admin inline. I have implemented a version of the Entity-Attribute-Value paradigm in my shop application (I tried eav-django and it wasn't flexible enough). In my model it is Product-Parameter-Value. Everything works as I want except that when including an admin inline for the Parameter-Value pair, the same input formfield is used for every value. I understand that this is the default Django admin behaviour because it uses the same formset for each Inline row. I have a callback on my Parameter that I would like to use (get_value_formfield). I currently have: class SpecificationValueAdminInline(admin.TabularInline): model = SpecificationValue fields = ('parameter', 'value') readonly_fields = ('parameter',) max_num = 0 def get_formset(self, request, instance, **kwargs): """Take a copy of the instance""" self.parent_instance = instance return super().get_formset(request, instance, **kwargs) def formfield_for_dbfield(self, db_field, **kwargs): """Override admin function for requesting the formfield""" if self.parent_instance and db_field.name == 'value': # Notice first() on the end --> sv_instance = SpecificationValue.objects.filter( product=self.parent_instance).first() formfield = sv_instance.parameter.get_value_formfield() else: formfield = super().formfield_for_dbfield(db_field, **kwargs) return formfield formfield_for_dbfield is only called once for each admin page. How would I override the default behaviour so … -
Why does Django not append a slash in auto generated URLs?
Ive noticed that almost all request hitting my server is redirected (HTTP 301): [pid: 23916|app: 0|req: 601/1916] x.x.x.x () {44 vars in 896 bytes} [Wed Sep 14 13:46:40 2016] GET /clinic_profile/11 => generated 0 bytes in 0 msecs (HTTP/1.1 301) 3 headers in 134 bytes (1 switches on core 0) [pid: 23917|app: 0|req: 416/1917] x.x.x.x () {44 vars in 898 bytes} [Wed Sep 14 13:46:40 2016] GET /clinic_profile/11/ => generated 69630 bytes in 286 msecs (HTTP/1.1 200) 3 headers in 102 bytes (1 switches on core 0) Note that Django appends a / to the URL. This behavior is activated through the APPEND_SLASH which defaults to True, as explained in the documentation. I've experienced unwanted behavior due to this redirect (e.g. double database hits). All the URLs in my system is generated through Django,: In urls.py: url(r'^clinic_profile/(?P<pk>\d+)/$', ClinicProfile.as_view(), name="clinic_profile"), In template: <a href=`{% url 'clinic_profile' pk %}`>Link</a> which compiles to: <a href="/clinic_profile/11">Link</a> (note the missing / at the end) Question: Why does Django not append a slash in the auto generated url?