for field in self.fields Or do I miss something ? ...
django-easy-thumbnails uses default renaming function. You can write your own naming function and set it in settings as a default naming function the library should use, as described here THUMBNAIL_NAMER: myapp.utils def namer(thumbnailer, prepared_options, source_filename, thumbnail_extension, **kwargs): # do something and return name pass settings.py THUMBNAIL_NAMER = 'myapp.utils.namer' ...
If your template is independent of apps, it shouldn't be in your app folder - namespace it accordingly. How do you load your template? Did you setup your templates/staticfolders in your settings.py? Updated For the fresh project you need to configure your settings.py file. Read here, ask away if you...
It looks like you're missing zlib; you'll want to install it: apt-get install zlib1g-dev I also suggest reading over the README and confirming you have all other dependencies met: https://github.com/dccmx/mysqldb/blob/master/README Also, I suggest using mysqlclient over MySQLdb as its a fork of MySQLdb and what Django recommends....
django,django-models,django-queryset
You should reverse the foreign key relationship: class HeartRate(models.Model): timestamp = models.DateTimeField('Date and time recorded') heartrate = models.PositiveIntegerField(default=0) exercise = models.ForeignKey(Exercise, related_name='heartrates') class Exercise(models.Model): start_timestamp = models.DateTimeField('Starting time') finishing_timestamp = models.DateTimeField('Finishing time') To get all of the heartrates of an exercise: heartrates = my_exercise.heartrates.all() ...
According to the Django documentation regarding static/: This should be an initially empty destination directory for collecting your static files from their permanent locations into one directory for ease of deployment; it is not a place to store your static files permanently. You should do that in directories that will...
You need sudo for the python command to write to /Library/Frameworks...: curl https://bootstrap.pypa.io/ez_setup.py -o - | sudo python ...
django,django-forms,django-templates,django-views
The Django admin uses AdminTimeWidget to display time fields, not the TimeInput widget that you are using in your code. There isn't a documented way to reuse the AdminTimeWidget outside of the Django admin. Getting it to work is very hacky (see the answer on this question, which is probably...
It looks like (re-reading your post it's not 100% clear) what you want is a partial application. Good news, it's part of Python's stdlib: import os from functools import partial def generic_upload_to(instance, filename, folder): return os.path.join(instance.name, folder, filename) class Project(TimeStampedModel): name = models.TextField(max_length=100, default='no name') logo = models.ImageField( upload_to=partial(generic_upload_to, folder="logo")...
The solution that worked for me was removing the below piece of code from settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] And adding : TEMPLATE_DIRS = ('C:/Users/vaulstein/tango_with_django_project/templates',) OR Changing the line...
Remove the comma on your first line of code, this turns it into a tuple optional_message = form.cleaned_data['optional_message'], should be optional_message = form.cleaned_data['optional_message'] ...
Instead of using hard coded CSS links <link href="static/bootstrap/css/bootstrap.min.css" rel="stylesheet"> Use Django Template Tags: Or you can also use below if you list.html is rendering yoursite.com/list/ <link href="../static/bootstrap/css/bootstrap.min.css" rel="stylesheet"> if yoursite.com/something/list/ then use; <link href="../../static/bootstrap/css/bootstrap.min.css" rel="stylesheet"> ...
python,django,forms,django-forms
You need to assign the field to form.fields, not just form. However this is not really the way to do this. Instead, you should make all your forms inherit from a shared parent class, which defines the captcha field....
Forking the repository clones the entire repository, not just the master branch. You can then checkout the tag you want to work on, make the required changes, and create a new tag. # checkout the tag git checkout tag_to_fork_from # alternatively, create a new branch starting with the tag git...
I've done this with a simple method in views.py. Simply retrieve the record, blank out its id then save and open it. Something like def create_new_version(request) : record = models.MyDocument.objects.filter(id=request.GET['id'])[0] record.id = None record.save() return http.HttpResponseRedirect(reverse('edit-mydocument', kwargs={'pk':record.id})) where MyDocument is your model and edit-mydocument is your UpdateView. Just call this...
I would use this: def _total_amount(self): req = QuoteRow.objects.filter(quote=self.pk) return sum([i.unit_price * i.quantity for i in req]) It takes one more line but it's clearer to me....
python,linux,django,web,frameworks
You can use the __range field lookup: start = datetime.date.today() end = start + datetime.timedelta(days=1) Model.objects.filter(datetime__range=(start, end)) ...
Since you need to pass variables from one view to another, you can set the value of grade and teacher in the session and then use this values in your second view to redirect it properly. request.session['grade'] = 5 request.session['teacher'] = 'smith' In your 2nd view, you can just do...
value.replace(/\s/g, '').split(",").join(", ") should work for all cases (anything other than one space after comma)...
Remove plugins you don't need from INSTALLED_APPS. Alternatively, in an app after all plugin apps in INSTALLED_APPS in either cms_plugins.py or models.py you can use cms.plugin_pool.plugin_pool.unregister_plugin to remove them from the pool: from cms.plugin_pool import plugin_pool from unwanted_plugin_app.cms_plugins import UnwantedPlugin plugin_pool.unregister_plugin(UnwantedPlugin) ...
Typically, as stated by @DanielRoseman, you certainly want to: Create a REST API to get data from another web site Get data, typically in JSON or XML, that will contain all the required data (name and surname) In the REST controller, Convert this data to the Model and save the...
There are two things that you need to change. In the views.py file, rather than returning 4 different lists, return a single zipped version of the lists like zipped_list = zip(first_list, second_list, third_list, fourth_list) Now this must be passed to the view file that is being rendered. context_dict = {'zipped_list':...
django,dependencies,database-migration,django-south
You should use the run_before attribute: class Migration(migrations.Migration): run_before = [ ('core_app', '0001_initial'), ] ...
Try adding to the Apache configuration file: WSGIApplicationGroup %{GLOBAL} See: http://code.google.com/p/modwsgi/wiki/ApplicationIssues#Python_Simplified_GIL_State_API As the log snippet shows the WSGI file at least being loaded, which would only happen if a request is received, the issue may that you are using third party extension modules for Python that will not work in...
django,python-2.7,django-forms
Your post method is returning the result of reverse, which is a string, ie the URL. You actually need to return a redirect response. The redirect shortcut can do this for you directly: from django.shortcuts import redirect ... def post(self, request, *args, **kwargs): ... return redirect('detail_pasta', hash=item.url) ...
django,django-models,django-admin
Try: when_first_upload = models.DateTimeField(default=datetime.datetime.now) You need the callable itself, not the result returned by it....
python,django,orm,django-admin
Django by itself doesn't provide access to the database-level users / groups / permissions, because it doesn't make much sense for a typical web application where all connections will be made with the same database user (the one defined in settings.DATABASES). Note that it's not a shortcoming be really the...
angularjs,django,django-templates
You can add the angular app as a simple template view in Django views.py def index(request): return render(request, 'yourhtml.html', {}) urls.py .... url(r'^your_url/$', views.index), .... Then the index.html file can have your angular code...
django,django-templates,django-views
Here's a basic approach you can tweak for your convenience: Add a first_image field to your model: class Blog(models.Model): title = models.CharField(max_length=150, blank=True) description = models.TextField() pubdate = models.DateTimeField(default=timezone.now) publish = models.BooleanField(default=False) first_image = models.CharField(max_length=400, blank=True) Now all you have to do is populate your first_image field on save, so...
POST are supposed to be for creation purpose. If you want to update with a ViewSet you'll need to PUT or PATCH (partial update) instead. Edit: For more about this, here's some explanation on the HTTP methods used for REST API: http://restful-api-design.readthedocs.org/en/latest/methods.html This is also described in the DRF documentation...
you didn't define user variable before using it def home(request): #user = request.user access_token = SocialToken.objects.get(account__user=request.user, account__provider='facebook') #get instead of filter (you need only one object) r = requests.get('https://graph.facebook.com/me?access_token='+access_token.token+'&fields=id,name,email') #add access_token.token to your request ...
python,django,python-2.7,memory,scrapy
You can process your urls by batch by only queueing up a few at time every time the spider idles. This avoids having a lot of requests queued up in memory. The example below only reads the next batch of urls from your database/file and queues them as requests only...
django.contrib.auth.login is the actual action of signing in the user. django.contrib.auth.views.login is a view that renders an HTML login form on GET request and handles POST request which internally calls django.contrib.auth.login....
json,django,django-templates,django-rest-framework
model.py: class Day(models.Model): date = models.DateField(default=date.today) def get_todo_list(self): return self.day_todo_set.order_by('-id')[:5] class ToDo(models.Model): date = models.ForeignKey(Day, related_name="day_todo_set") name = models.CharField(max_length=100) very_important = models.BooleanField(default=False) finished = models.BooleanField(default=False) In serializers.py class ToDoSerializer(serializers.ModelSerializer): class Meta: model = ToDo field = ('id', 'date', 'name', 'very_important', 'finished') class...
python,django,rest,file-upload,request
I tried to fix this but in the end it was quicker and easier to switch to the Django-REST framework. The docs are so much better for Djano-REST that it was trivial to set it up and build tests. There seem to be no time savings to be had with...
django,django-templates,django-views
You need to define a custom template tag which returns the type of data. from django import template register = template.Library() @register.filter def data_type(value): return type(value) Then use it inside your template like this: {% for key, value in leasee.items %} <p> {{key}} </p> <ul> {%if value|data_type == 'dict' %}...
Django ModelForm have widgets attribute and also you can use forms widgets PasswordInput for password field let's assume you already have working view..so I skip the full view here #views.py form = UserForm(request.POST, instance = user) set the widgets like #forms.py widgets = { 'password':forms.PasswordInput(render_value = True), } And using...
mysql,django,spatial,geodjango
Yes , It's that simple but you will have some spatial limitations
First, thanks for trying Spyne out! Answers: Try return ResponseData(codResultado=1234, message="Hello!") Pass _out_response_name to @rpc Don't invent yours and use the built-in Fault class. Spyne docs are bad, yes, but they aren't THAT bad. Read them :) Spyne also has a mailing list: http://lists.spyne.io/listinfo/people Hth,...
django,unit-testing,django-views,django-rest-framework,django-testing
RequestFactory and Client have some very different use-cases. To put it in a single sentence: RequestFactory returns a request, while Client returns a response. The RequestFactory does what it says - it's a factory to create request objects. Nothing more, nothing less. The Client is used to fake a complete...
If I understand you correctly, you want to make a custom Admin Action? If so, start with the Django documentation for it. Then Have a look at these two use cases: Admin Action with parameters Admin Action with intermediate pages ...
Check out The Http404 Exception docs: For convenience, and because it’s a good idea to have a consistent 404 error page across your site, Django provides an Http404 exception. If you raise Http404 at any point in a view function, Django will catch it and return the standard error page...
python,django,django-templates
I think you might be looking for render_to_string. from django.template.loader import render_to_string context = {'foo': 'bar'} rendered_template = render_to_string('template.html', context) ...
django,apache,file-upload,passenger
Passenger author here. Try setting passenger_log_level to a higher value, which may give you insights on why this is happening. I don't know which Passenger version you are using, but in version 5, the Passenger request processing cycle looks like this: Apache receives the request. Once headers are complete, it...
First of all I would change the following: try: blogs = paginator.page(page) except(EmptyPage, InvalidPage): blogs = paginator.page(page) # Raises the same error But you could pass a range within your context. index = paginator.page_range.index(blogs.number) max_index = len(paginator.page_range) start_index = index - 3 if index >= 3 else 0 end_index =...
Hope the following helps: for i, record in enumerate(qs): record.value = i ...
django,many-to-many,django-queryset
You're very close: Change: [i.dealership for i in q.dealership.all] to: [dealership for dealership in q.dealership.all()] Here's sample output from one of my model's M2M relationships on a project which demonstrates what you should see from the list comprehension. shared_with is an M2M field to a model called Profile: >>> from...
django,api,rest,django-rest-framework,serializer
By default DRF will look at an attribute on the User model named after the serializer's field (member here). However the related name is profile. This can be worked around by passing the source="profile" to your MemberProfileSerializer....
django,django-models,django-middleware
You are trying to match a foreign key to a string, you need to provide the model ProductPart.objects.values().filter(part=v) Note: the values isn't necessary either ProductPart.objects.filter(part=v) From the documentation for Values a QuerySet subclass that returns dictionaries when used as an iterable, rather than model-instance objects. In other words, you are...
django,django-admin,django-settings
Make sure you have added 'django.contrib.sites' to your INSTALLED_APPS, then run migrate to create the required table. python manage.py migrate ...
python,django,osx,python-2.7,python-3.x
Recommended: Try using virtualenv and initiate your environment with Python3. Or a quicker solution is to use python interpreter directly to execute django-admin: <path-to-python3>/python /usr/local/bin/django-admin startproject mysite ...
It looks like your plural are in the wrong spot: {% for post_images in post.sellpostimage_set.all %} should be: {% for post_image in post.sellpostimage_set.all %} post_image = SellPostImage.objects.filter(post=poster_posts) context_dict['post_image'] = post_image should be: post_images = SellPostImage.objects.filter(post=poster_posts) context_dict['post_images'] = post_images or: post_image = SellPostImage.objects.get(post=poster_posts) context_dict['post_image'] = post_image why do you do this...
Django templates do not use inclusion so much as template inheritance. The idea is you set up a hierarchy of templates, specializing some common thing. For instance: you could have a base.html that has some basic page structure, common to all pages of your website. you could then have a...
There is no {% switch %} tag in Django template language. To solve your problem you can either use this Django snippet, that adds the functionality, or re-write your code to a series of {% if %}s. The second option in code: {% if property.category.id == 0 %} <h4>'agriculture'</h4> {%...
django,rest,django-models,django-rest-framework,imagefield
As noted in the docs, .update() doesn't call the model .save() or fire the post_save/pre_save signals for each matched model. It almost directly translates into a SQL UPDATE statement. https://docs.djangoproject.com/en/1.8/ref/models/querysets/#update Finally, realize that update() does an update at the SQL level and, thus, does not call any save() methods on...
You could have a model VideoComponent with a position field as well as foreign keys to VideoClipModel and ImageModel. Then a Video model would have a many to many field to VideoComponent. class Video(models.Model): components = models.ManyToManyField('VideoComponent') class VideoComponent(models.Model): image = models.ForeignKey('ImageModel') video_clip = models.ForeignKey('VideoClipModel ') position = models.IntegerField() class...
django,checkbox,django-templates,django-views
views.py if request.method == 'POST': #gives list of id of inputs list_of_input_ids=request.POST.getlist('inputs') Hope this solves pretty much of your problem.Check out this link Checkboxes for a list of items like in Django admin interface ...
python,django,django-templates
Your problem is with your settings. You currently have: TEMPLATE_DIRS = ( os.path.join(BASE_DIR, 'templates'), ) This is how you set up template directories in Django 1.7.x and below. In Django 1.8.x, change your TEMPLATES [] to read like this: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), ],...
This can be achieved using django filters. But we will have to code our own custom filter. Include this in the views file from django.template.defaulttags import register @register.filter def get_item(dictionary, key): return dictionary.get(key) In the html file you can add the following line. We are passing the dictionary and key...
Invoke django-admin.py like this python django-admin.py, in your activate virtualenv. Alternatively you can do /path/to/virtualenv/bin/python django-admin.py. The best solution is probably adding a shebang to django-admin.py that looks like #!/usr/bin/env python which should use the python interpreter of your active virtualenv. See http://stackoverflow.com/a/2255961/639054
Save the form with commit=False, edit the returned instance, then save it to the db. if request.POST: f = Create_EventForm(request.POST) if f.is_valid(): event = f.save(commit=False) event.other_value = lookup_value() event.save() See the doc's on ModelForm's save method for more info....
You should be able to create a different FileSystemStorage instance for each storage location. Alternatively, you could write a custom storage system to handle the files....
javascript,jquery,html,django,django-templates
Every photo has the same id for its like count: {% for photo in photos %} <a href="#" id="like_count">0</a> {% endfor %} Therefore, only the first is recognized as the 'real' #like_count Since you have a primary key for the photo, you could make the ids distinct by incorporating the...
You need this documentation from Django, I guess you are missing the CSRF Token in your POST data.
python,sql,django,sorting,django-orm
The above algorithm would not work , because assume you have the following list - [0,2,5,9] You should ideally get - [0,1,2,3] The sum of that list is 6 , but the length of the list is 4 , this does not meet your condition in is_compressed() . The algorithm...
python,django,django-views,django-rest-framework,django-urls
You can't access request on urls.py, see: How Django processes a request You can configure versioning on django-rest-framework and get version on request object like: class SampleView(APIView): def post(self, request, format=None): if request.version == '1': return Response(status=status.HTTP_410_GONE) Or use URLPathVersioning approach....
z="12345678 912345678 15235213523 23512351235" print re.sub(r"^(.{20})",r"\1 ",z,flags=re.UNICODE) ...
You may be editing an existing object, right? I would simply exclude it from the result set: def clean_number(self): """Ensures the new Number is unique """ enteredNumber = int(self.cleaned_data['number'], 8) queryset = Number.objects.filter(number=enteredNumber) if self.instance is not None and self.instance.pk is not None: queryset = queryset.exclude(pk=self.instance.pk) if queryset.exists(): raise forms.ValidationError("Error")...
python,django,django-rest-framework
This error: File "/tutorial/tutorial/urls.py", line 9, in <module> url(r'^admin/', include(snippets.urls)), NameError: name 'snippets' is not defined occurs because snippets.urls has to be quoted. See the example here: urlpatterns = [ url(r'^', include('snippets.urls')), ] As shown here, you could write something like this: from django.contrib import admin urlpatterns = [ url(r'^polls/',...
Forgive me to digress a little, but I can't help but wonder use could have gotten away with far less code, than you have if you had created a serializer and used a class-based view. Besides, if you had just created email as EmailField of serializer it would have automatically...
Assuming Place has a name field, the following should do what you want. def __unicode__(self): return u'%s | %s' % (self.departure, ", ".join(l.name for l in self.landing.all())) Depending on how many records you have and how many relationships, it might cause a performance hit, so be careful....
python,html,django,templates,django-1.4
You can use the include tag in order to supply the included template with a consistent variable name: For example: parent.html <div class="row"> <div class="col-md-12 col-lg-12 block block-color-1"> {% include 'templates/child.html' with list_item=mylist.0 t=50 only %} </div> </div> child.html {{ list_item.text|truncatewords:t }} UPDATE: As spectras recommended, you can use the...
python,django,list,parameters,httprequest
Since, request.GET is a dictionary, you can access its values like this: for var in request.GET: value = request.GET[var] # do something with the value ... Or if you want to put the values in a list: val_list = [] for var in request.GET: var_list.append(request.GET[var]) ...
When migration created, you can manually change the base migration class to your custom subclass with overridden apply method from django.db import migrations class MyBaseMigration(migrations.Migration): def apply(self, project_state, schema_editor, collect_sql=False): for operation in self.operations: """ Examine operation classes here and provide end-user notes """ return super(MyBaseMigration, self).apply(project_state, schema_editor, collect_sql=collect_sql) ...
python,django,timezone,countries,django-countries
You need to setup a custom Country model. Lets say you have an app 'mygeonames' with models.py: import cities_light from django.db import models from cities_light.settings import ICountry from cities_light.receivers import connect_default_signals from cities_light.abstract_models import (AbstractCountry, AbstractRegion, AbstractCity) class Country(AbstractCountry): capital = models.CharField(max_length=50) connect_default_signals(Country) class Region(AbstractRegion): pass connect_default_signals(Region) class City(AbstractCity): pass...
It looks like you're running against the system version of python on the new laptop, rather than the virtualenv, so it is probably a different version. You can check this by looking at the version of Python on the virtualenv in the old laptop and the new laptop with python...
Your SignUpView is not specifying the form it should render, you need to add the form_class attribute. class SignUpView(CreateView): form_class = RegistrationForm model = User template_name = 'accounts/signup.html' ...
django,django-models,django-forms,django-templates,django-views
Your form inherits from forms.Form, which does not know anything about models and ignores the Meta class. You should inherit from forms.ModelForm.
python,django,session,cookies,python-requests
The following code is working perfectly fine for me - import requests from bs4 import BeautifulSoup s = requests.session() r = s.get('http://www.jstor.org/stable/pdf/10.1086/512825.pdf') soup = BeautifulSoup(r.content) pdfurl = 'http://www.jstor.org' + soup.find('a', id='acptTC')['href'] with open('export.pdf', 'wb') as handle: response = s.get(pdfurl, stream=True) for block in response.iter_content(1024): if not block: break handle.write(block) ...
python,django,osx,notifications,vagrant
Why not run a SSH server on the VM and connect from the host via a terminal? See MAC SSH. Which OS is running on the VM? It should not be too hard to get the SSH server installed and running. Of course the VM client OS must have an...
python,django,django-templates,django-views
You cannot do this like that. Views are glorified functions. They have a single entry point (dispatch()) that is invoked by Django internals, and invokes the correct method on itself, depending on the HTTP method (here, get()). Casting the view to a string will just display its name, not call...
Maybe you could decorate your test with @unittest.skipIf(condition, reason) and test for the presence of a Travis CI specific environment variable to skip it or not. E.g. import os ... @unittest.skipIf("TRAVIS" in os.environ and os.environ["TRAVIS"] == true, "Skipping this test on Travis CI.") def test_example(self): ... ...
django,django-forms,django-crispy-forms
You shouldn't check the checkbox, but check the value of the file input field. If it is False, then you can delete the file. Otherwise it is the uploaded file. See: https://github.com/django/django/blob/339c01fb7552feb8df125ef7e5420dae04fd913f/django/forms/widgets.py#L434 # False signals to clear any existing value, as opposed to just None return False return upload ...
In your view, you need to provide the following: lookup_field -> Most probably the ID of the record you want to update lookup_url_kwarg -> The kwarg in url you want to compare to id of object You need to define a new url in your urls.py file. This will carry...
Don't know what field you want to filter, but you could do it like this: class A(forms.ModelForm): class Meta: model = ModelA def __init__(self, *args, **kwargs): super(A, self).__init__(*args, **kwargs) self.fields['your_field'].queryset = self.fields['your_field'].queryset \ .filter(some_filter_value=1) ...
django,django-cms,django-migrations
Note these models don't have any migrations. That's your problem right there. The way you are using CMSPlugin as a base for your new model requires that your model be subject to migration because CMSPlugin is also subject to migrations. The documentation says: Be aware, however, that unmigrated apps...
Try using celery worker... instead of celery multi... - since it does not daemonize it is easier to see error messages etc. On a related note, from experience I would recommend using supervisord to spawn celery worker processes instead of using multi at all. ...
python,django,django-templates,django-template-filters
Your problem is with your if/else tags. You have this: {{ % if ... %}} ... {{% else %}} ... First off, you need to surround if/else by {% %}, not {{% %}}. Secondly, you don't have an endif. An if/else block should look like this: {% if ... %}...