w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
  Home » DJANGO » Page 1
Webfaction setup Virtualenv
Webfaction provides instructions on how to install pip and pip packages for use within your local home directory... http://docs.webfaction.com/software/python.html#installing-packages-with-pip If you plan on hosting multiple web applications from the same webfaction server, it's probably wise to setup virtualenvs for each application. To do this, I would try the following... pip install --user

Categories : Django

Django form doesn't output custom class attributes for inputs
You need to use your custom form in your view. If you don't specify a form_class for CreateView, django will create one for you: from django.views.generic.edit import CreateView, UpdateView, DeleteView from myapp.models import MyModel class MyModelCreate(CreateView): model=MyModel form_class = MyBaseForm def get_context_data(self, **kwargs): context=super(MyModelUpdate, self).get_conte

Categories : Django

Accessing form variables in Meta, Django Floppyforms
You can define those attributes via the field's widget from django.forms.widgets import TextInput def __init__(self, *args, **kwargs): self.placeholder = "Chapter %s" % kwargs.pop('number') super(ChapterForm,self).__init__(*args, **kwargs) self.fields['name'].widget = TextInput(attrs={ 'class': "headline", 'placeholder': self.placeholder });

Categories : Django

Use of "if" in template with custom template tag with multiple arguments
Set the result of the template tag call to a variable then call {% if %} on that result {% hs_get_section_answer questionnaire 'abc' 'def' 'ghi' 'jkl' as result %} {% if result %} ... {% endif %} You will also need to change your template tag to use an assignment tag instead of a simple tag as well. See assignment tags django doc: https://docs.djangoproject.com/en/dev/howto/custom-template-tags

Categories : Django

Different between django object.related.id and object.related_id
object.relation.id will retrieve (if not already) relation model instance from database, and then return value of id field. object.relation_id will not do any additional query to database, as relation_id is stored in object model instance level.

Categories : Django

Gunicorn on lighttpd - changing base URL for static files from localhost:8080
I am new to django/gunicorn too but here is how I configured my app: settings in settings.py STATIC_ROOT = "/path to static files" STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) I'm not using lighttpd but nginx and here is the configuration: server{ server_name example.com www.example.com; access_log off; location /static { autoin

Categories : Django

Django sites' response time variance
Solved it: it was gunicorn's "max-requests" setting, spawning a new worker every X connections. When X is ten and I'm hitting a "quiet" site, the long response time is every ten hits. That's why I only noticed the multi-modal times on some Django sites: the others were presumably busy or not using gunicorn.

Categories : Django

Redirect to next URL in django FormView
Include the data as GET parameters in your success url. def get_success_url(self): # find your next url here next_url = self.request.POST.get('next',None) # here method should be GET or POST. if next_url: return "%s" % (next_url) # you can include some query strings as well else : return reverse('home') # what url you wish to return Hope this will work for you.

Categories : Django

[Solved]Getting error while connecting to database with freetds and odbc connection
You need to define your Data Source name under Databases settings which is in settings.py file. DATABASES={ 'default': { 'OPTIONS':{ 'DRIVER':'FreeTDS', 'DSN': 'YOUR DSN NAME' }, }, }

Categories : Django

Unicode issue updating User model with a custom Form
Look veeery closely at the following lines: user.username = form.cleaned_data['username'], user.first_name = form.cleaned_data['name'], user.last_name = form.cleaned_data['lastname'], Do you see it? Yes, it's that comma at the end. It's creating a tuple. Stop doing that.

Categories : Django

Django allow user to edit their profile
after login(request, user) you can access the User info from _auth_user_id in session like request.session[_auth_user_id] . So you can make a function like edit profile def edit_profile(request): template_var = {} if '_auth_user_id' in request.session: userId = request.session['_auth_user_id'] new_profile_user = Profile.objects.get(user_id=userId) userDetails = Use

Categories : Django

How to save date/time with Django form
Well, when you submit the form, you will get the value for ridetime in cleaned_data as an datetime object which will look like this 2014-11-18 00:00:00. You can save that object directly to model if your model field is DateTimeField. The way you are saving the value of ridetime in views.py should work fine. So using SelectDateWidget will only get you the date when you submit the form. If you wan

Categories : Django

Django-tables2: how to order_by accessor
For function like Model's property method, you can access it directly using accessor. For example: Class MyModel(models.Model): data= models.CharField(max_length=255) @property def print_function(self): return 'hello world' #Table class class MyTable(tables.Table): data= tables.Column(accessor='print_function') class Meta: model = MyModel fields =

Categories : Django

Running multiple Django tests via one ./manage.py test command causes error, running each individually does not
Found the answer: Regardless of how many different test cases are run during one ./manage.py test call, and regardless of how much the database is rolled back/truncated (for TestCase and TransactionTestCase, respectively) between tests, all tests are run under the same python thread and with the same instantiations of all model base classes. Thus any variables in the thread or any modifications

Categories : Django

Foriegn key returning DoesNotExist after schemamigration
What needed to be done was a data transformation within the migration file, which required some customization class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Foo.id' db.add_column(u'foo', 'id',

Categories : Django

Django Project with Multiple Apps on Heroku
What's the disadvantage of scaling the entire project? It doesn't matter if the dyno serves one app or many: it's the number of requests overall that counts. An app isn't really a discrete thing in Django terms, it's just a collection of models and views, and it doesn't make much sense to try and separate them. Separate services connected by REST are a really great thing - my own projects often wo

Categories : Django

How can I read a file in django template on client side
Django is pure Python. This is something that helps to remember when using the Templates. Just read the file, and send it to the template as context. Example: def myview(request): context = {file: open('myfile.txt', 'r').read()[:250]} return render(request, 'mytemplate.html', context) That should do the trick. You may need to add some extra formatting to the file before rending it

Categories : Django

Redshift as a Web App Backend?
Redshift (ParAccel) is an OLAP-optimised DB, based on a fork of a very old version of PostgreSQL. It's good at parallelised read-mostly queries across lots of data. It's bad at many small transactions, especially many small write transactions as seen in typical OLTP workloads. You're partway in between. If you don't mind a data loss window, then you could reasonably accumulate data points and ha

Categories : Django

complex SQL syntax
I think I will use CTE though It has not been tested WITH last_actions AS ( SELECT DISTINCT userId, MAX(aDate) as last_logged FROM user_actions GROUP BY userId ORDER BY userId) SELECT a.userId, COUNT(b.pDate) FROM last_actions a, prizes b WHERE b.pDate >= a.last_logged GROUP BY a.userId;

Categories : Django

Restricted set of nested fields in a django REST framework ModelSerializer
You can do this by creating your own serializer to use as the nested serializer. class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ('name', 'email', ) You are better off with creating specialized serializers instead of relying on Django REST Framework to create them for you. By default, serializers that are automatically created cont

Categories : Django

Integrating django-filer into djangocms-text-ckeditor
It seems to me that cmsplugin-filer provides what you are looking for. Take a look at the screenshot. From within the ckeditor modal, I can browse django-filer files and integrate them. Is that what you were looking for?

Categories : Django

How to use select widget for Charfield in UpdateView
The select widget may need your choices passed to it, as per the documentation. If you need to fetch the choices with each page request, you could adjust the widget in the form constructor like so: class UpdateItemForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(UpdateItemForm, self).__init__(*args, **kwargs) self.fields['name'].widget.choices = Name.objects.

Categories : Django

django - i18n - how is it possible?
Django i18n is build in such a way, that if url contains a language prefix, then exactly that language will be shown. But, if you'll remove the language prefix from url, then django will discover the user's preferred language first and then show corresponding version of a page. So, in your case i think the best way would be to create a share button or maybe show the url for sharing on page. User

Categories : Django

Adding cms function on my existing django site
FeinCMS (http://www.feincms.org/) is pretty easy to integrate into an existing web site. By just adding a couple of lines in your settings.py and defining a Page model, you would have a working CMS. It doesn't require a lot of "template refactoring". FeinCMS has a basic blogging module (http://www.feincms.org/plugins/). Django-CMS is a nice one as well (especially the killing front-end editing f

Categories : Django

Django associate a model with a "generic" object
You can leverage the Django Content Type framework to accomplish exactly what you need. See generic relations in Django documentation.

Categories : Django

django ModelMultipleChoiceField set initial values
You can pass it the "initial" setting from your view. For example: form = FormUsingCategory(initial={'category':querysetofinitialvalues}) The tricky part is that you must have the right queryset. Just like the seed values, it must be of Category.objects.filter(...) - anything else won't work.

Categories : Django

Migrations failing on Heroku
im not so sure on that one, but after you ran the Migration, the file created: 0002_entry_content_placeholder.py is as you notice, the second migration file. If its an option for you, you could try to delete/rename the migration folder/files and run makemigrations again. I got kinda the same error some time ago, and if i remember right, that did the trick. Sorry for bad english

Categories : Django

Create a new resouce and its relations in one go in django rest framework
DRF expected attribute field by default, because you didn't define field names explicitly. Define all you fields, like this: class ValueSerializer(serializers.ModelSerializer): class Meta: model = Value fields = ('name',) class AttributeSerializer(serializers.ModelSerializer): allowed_values = ValueSerializer(many=True) class Meta: model = Attribute

Categories : Django

Why do I get 'invalid literal for int()' when running my query?
Without seeing your urls.py it's hard to say for sure, but I'm guessing your URL pattern has something like: url(r'^reviews/([d]+)$', views.show_reviews), when it needs to have something like: url(r'^reviews/([w]+)$', views.show_reviews), or url(r'^reviews/(.+)$', views.show_reviews), Either that or your UserReview object's name field is an int when it should be a string. Perhaps post mo

Categories : Django

Django create superuser from batch file
As it seems you can't provide a password with the echo ''stuff | cmd, the only way I see to do it is to create it in Python: python manage.py syncdb --noinput echo "from django.contrib.auth.models import User; User.objects.create_superuser('admin', 'admin@example.com', 'pass')" | python manage.py shell python manage.py runserver

Categories : Django

Why does my query in views.py give me a a TypeError?
According to the configured url: url(r"^reviews/(?P<username>w+)/$", show_reviews) you are capturing username from the URL. Your view should have it as an argument: def show_reviews(request, username): ...

Categories : Django

Alter menu title Django-cms
you could override the get_menu_title() but better dont touch core things. instead use the slice template filter {{ child.get_menu_title|slice:':1' }}

Categories : Django

Django form and field validation does not work?
Your form should be submitting to itself. Meaning, if the form is on /union/contact/, you should be POSTing to /union/contact/. Currently, you have it submitting to a different view/url. The problem is arising because your form processing is happening in the FormView, not at your success_url(). You need to POST to the view that is actually responsible for the validation of the form (in this case,

Categories : Django

How to import data into django app from files best way
I believe this is happening because the script needs to be run within the context of your Django application and using your settings file. This answer shows a good example of doing this for Django 1.7+ Runtime error:App registry isn't ready yet Or for pre Django 1.7, put this at the top of your script and edit paths accordingly... import sys, os sys.path.append('/path/to/your/django/app') o

Categories : Django

Custom output with serializer in Django Rest Framework
The method you are looking for is to_native. class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email', 'is_staff') def to_native(self, obj): return 'some custom response' Note that to_native is renamed to to_representation in Django Rest Framework 3.0

Categories : Django

How to iterate dictionary objects in template
You can use dict.items method. In python 2.x better use dict.iteritems instead. {% for y_key, yr in archives.items %} <li>{{ yr.year }} &nbsp;({{ yr.count }})</li> {% for m_key, mth in yr.months.items %} <li>&nbsp;&nbsp; - {{ mth.month_name }} &nbsp; ({{ mth.count }})</li> {% endfor %} {% endfor %}

Categories : Django

Django Reverse Accessor Clashes
related_name's must be unique. You're giving the same name to all the related_name's. Try to rename them like this: user = models.OneToOneField(User, related_name="custom_user_profile", primary_key=True) #.. provider = models.OneToOneField(Provider, related_name='user_ind_provider_profile') #.. provider = models.OneToOneField(Provider, related_name='user_org_provider_profile')

Categories : Django

the field name of OneToOneField field is append `_id` after the variable name
Django appends the _id for you in case of referential model fields. From the documentation of Database Representation of a model field: Behind the scenes, Django appends "_id" to the field name to create its database column name. You can change this explicitly by specifying db_column However, your code should never have to deal with the database column name, unless you write custom SQL

Categories : Django

How to make and submit multiple django forms
I would take a look at Django formsets. It's exactly the behavior you are looking for I believe. https://docs.djangoproject.com/en/dev/topics/forms/formsets/

Categories : Django




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.