Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't get MySQL/MariaDB to work with Django 1.10.1 and Python 3.5 on Fedora 24?
Besides the above, I'm using virtualenv and virtualenvwrapper. MariaDB server 10.1.17 was installed via dnf install I'm working through the first Django tutorial. My runserver command: (djTut3)$ python manage.py runserver ran OK, with a warning about migration. In part 2, here: https://docs.djangoproject.com/en/1.10/intro/tutorial02/ I ran: (djTut3)$ python manage.py migrate as instructed, and got the following errors: ImportError: No module named 'MySQLdb' During handling of the above exception, another exception occurred: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb' I did a lot of searching, and tried the below (among other things), mostly from SO: === $ sudo dnf install MySQL-python <No error> $ python3 manage.py migrate <Same errors as before> $ sudo dnf install mariadb-devel Skipping packages with conflicts: (add '--best --allowerasing' to command line to force their upgrade) $ sudo dnf install mariadb-devel --best --allowerasing <No error> $ python3 manage.py migrate <Same errors as before> $ pip3 install mysql-python ImportError: No module named 'ConfigParser' $ pip3 install mysql-connector <No error> $ pip3 install mysql-client _mysql.c:40:20: fatal error: Python.h: No such file or directory #include "Python.h" compilation terminated. error: command 'gcc' failed with exit status 1 $sudo dnf install python-devel mysql-devel <already installed> === Now I still can't get (djTut3)$ … -
django rest framework - how use default_timezone?
field in my serializer: date_from = serializers.DateTimeField(default_timezone=settings.TIME_ZONE) my settings.py: TIME_ZONE = 'Europe/Moscow' data in admin site: my screenshot and date in response: "date_from": "2016-12-23T21:00:00Z" Okay, i understand, what he return me time in UTC, but how i can get time in my timezone? Only use SerializerMethodField? -
Content of a Django template disappear immediately after rendering
I am trying to create an account detail page that shows some attributes of an Account- object. I have a view that is passing the object to be rendered in a template. In Firefox the rendered page doesn't show the attributes at all while in chrome you can see them for a second after which they disappear. I am using Django 1.7.1 and Python 2.7. Thank you in advance! Here's my code, it is based on the Ultimate Django course material: views.py: @login_required() def account_detail(request, uuid): account = Account.objects.get(uuid=uuid) if account.owner != request.user: return HttpResponseForbidden() variables = { 'account': account, } return render(request, 'accounts/account_detail.html', variables) models.py: class Account(models.Model): uuid = ShortUUIDField(unique=True) name = models.CharField(max_length=80) desc = models.TextField(blank=True) address_one = models.CharField(max_length=100) address_two = models.CharField(max_length=100, blank=True) city = models.CharField(max_length=50) state = models.CharField(max_length=2) phone = models.CharField(max_length=20) owner = models.ForeignKey(User) created_on = models.DateField(auto_now_add=True) class Meta: verbose_name_plural = 'accounts' def __unicode__(self): return u"%s" % self.name @models.permalink def get_absolute_url(self): return 'account_detail', [self.uuid] @models.permalink def get_update_url(self): return 'account_update', [self.uuid] @models.permalink def get_delete_url(self): return 'account_delete', [self.uuid] account_detail.html: {% extends 'base.html' %} {% block content %} <div id="content-container" class="container p-none"> <div id="ad-container"> <div id="gi-container" class="ad-container"> {% include 'accounts/account_item_view.html' %} </div> </div> {# List Contacts #} {# List Communications #} … -
any middleware in django to perform the abilities of security.yml in symfony2?
Can i declare the auth for all the apis in django, group wise from one file just like security.yml allows us in symfony2 -
How can i route my URL to a common method before passing passing to actual view in Django
Here is my code looks like :- url.py file :- from rest_framework import routers from view_user import user_signup,user_login router = routers.DefaultRouter() urlpatterns = [ url(r'^api/v1/user_signup',csrf_exempt(user_signup)), url(r'^api/v1/user_login',csrf_exempt(user_login)) ] view_user.py file:- def user_signup(request): try: if request.method == 'POST': json_data = json.loads(request.body) return JsonResponse(result, safe=False) except Exception as e: logger.error("at method user : %s", e) So, when I call the url:- http://myserver/api/v1/user_signup it goes to "user_signup" method of view_user.py file. But what I want is I should be able validate my request before it goes to the user_signup method. I want this validation for all the requests that comes to my server for all methods (ex:- user_signup,user_login ...) before it goes to respective methods. -
n+1 queries in dehydrated method of m2m resource in tastypie
We have a tastypie resource that depends on some other resource through m2m relationship. Now we are doing some work in save_m2m, something like below def save_m2m(self, bundle): super(ourResource, self).save_m2m(bundle) //some work return bundle and after before sending any data to client, it goes into dehydrate of m2m resource and under that, it have code something like self.m2m_resources = [] m2m_dehydrated = [] # convert the_m2ms to a QuerySet if it isn't already if type(the_m2ms) != QuerySet: the_m2ms = the_m2ms.all() # expects a QuerySet unlike super dehydrate method for m2m in the_m2ms: m2m_resource = self.get_related_resource(m2m) m2m_bundle = Bundle(obj=m2m, request=bundle.request) self.m2m_resources.append(m2m_resource) m2m_dehydrated.append(self.dehydrate_related(m2m_bundle, m2m_resource, for_list=for_list)) Now in it the last time self.dehydrate_related is causing n+1 queries since it executes each time the execute runs. Also we have already done prefetch_related on our querySet in Meta class. Something like class Meta: detail_allowed_methods = ['patch'] list_allowed_methods = ['get', 'post'] queryset = table.objects.using('default').select_related('table2') \ .prefetch_related( Prefetch('table3', queryset=table3.objects.select_related('table4', 'cols') .prefetch_related('options', 'options__options') .only(*FIELDS_TO_QUERY_API) ), Prefetch('items', queryset=Item.objects.select_related('item_data') .only(*FIELDS_TO_QUERY_API) ), 'tableX', 'tableX__options' )\ .only(*FIELDS_TO_QUERY_PM_API) fields = (... our fields ...) serializer = UJsonSerializer() validation = ModelFormValidation(form_class=resourceForm) always_return_data = True ordering = ['started_at'] filtering = { 'status': ('in',) } cache = OnlyCacheHeaders() And currently n+1 queries happening when we do … -
How to recover records in inline Django 1.4?
I work with Django 1.4. I have class class AdvertisingCampaignHit(models.Model): acampaign = models.ForeignKey( 'AdvertisingCampaignNew', db_column='acampaign_id' ) plf = models.ForeignKey( 'Platform', db_column='plf_id', limit_choices_to={'alias': 'tvz'} ) hit = models.IntegerField( default=0, null=True, blank=True ) Here is Platform table CREATE TABLE `platform` ( `id` int(11) NOT NULL AUTO_INCREMENT, `alias` varchar(3) NOT NULL, `description` varchar(512) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `platform_alias_unique` (`alias`) ) ENGINE=InnoDB AUTO_INCREMENT=248 DEFAULT CHARSET=utf8 | And here is table for my class AdvertisingCampaignHit CREATE TABLE `acamp_hit` ( `id` int(11) NOT NULL AUTO_INCREMENT, `acampaign_id` int(11) DEFAULT NULL, `plf_id` int(11) DEFAULT NULL, `hit` tinyint(1) DEFAULT '0', PRIMARY KEY (`id`), KEY `acampaign_id` (`acampaign_id`), KEY `plf_id` (`plf_id`), CONSTRAINT `acamp_hit_ibfk_2` FOREIGN KEY (`plf_id`) REFERENCES `platform` (`id`), CONSTRAINT `acamp_hit_ibfk_1` FOREIGN KEY (`acampaign_id`) REFERENCES `acampaign` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8 | Now I need to show in Django admin Inline info using the following structure: iOS: 255 hit Android: 100 hit Where iOS and ANdroid are 'alias' field in 'platform' table. We should count total value of hits for each platform. -
Django-allauth socialaccount provider_login_url has NULL for process, scope and params
I'm using Django 1.10.1 and allauth 0.27.0. I have enabled social network logins for google but have NULL for link parameters. Configuration: Settings.py (shortened) INSTALLED_APPS = [ ... skipped ... 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', ] AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email' ], 'AUTH_PARAMS': { 'access_type': 'online' } } } LOGIN_REDIRECT_URL = '/members/' LOGOUT_URL = '/' ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_SIGNUP_PASSWORD_VERIFICATION = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_USERNAME_REQUIRED = False SOCIALACCOUNT_QUERY_EMAIL = ACCOUNT_EMAIL_REQUIRED ACCOUNT_LOGOUT_ON_GET = True urls.py (shortened) url(r'^accounts/', include('allauth.urls')), client id and secret key are also configured on /admin/socialaccount/socialapp/ On login page I have: (shortened) {% load i18n l10n widget_tweaks account socialaccount staticfiles %} {% get_providers as socialaccount_providers %} {% for provider in socialaccount_providers %} <li> <a title="{{ provider.name }}" class="socialaccount_provider {{ provider.id }}" href="{% provider_login_url provider.id process=process scope=scope auth_params=auth_params %}">{{ provider.name }}</a> </li> {% endfor %} When I hit the login page I see provider's url like: http://127.0.0.1:8000/accounts/google/login/?process=NULL&scope=NULL&auth_params=NULL in {{ socialaccount_providers }} I have [<allauth.socialaccount.providers.google.provider.GoogleProvider object at 0x051A6E30>] What I do wrong? -
django manytomanyfield protect from delete
After days struggling with this, I finally reached to a conclusion. But I want to discuss the best approach or solution to this. I have a ModelA that has a M2M field to ModelB. I want to forbid deletion of objects of ModelB that has relations. M2M has no attribute on_delete=models.PROTECT and the way to achieve this is via through=othermodel. By this way, I don't view the values of the field in admin or in templates. And then I need to copy data to the new intermediary model. I think is simpler to use pre_delete signal to prevent deletion if it has relations. As seen on Using Pre_delete Signal in django if instance.model_set.all().exists(): raise IntegrityError("Forbidden: It has relations.") What do you think is the best way? There is another solution? -
Django : reverse is not resolving url for inbuilt password reset.
I want to use inbuilt password reset from Django. My urls.py is as follows. app_name = 'appname' urlpatterns= [ #urls ] urlpatterns += [ url(r'^resetpassword/passwordsent/$', password_reset_done, name='password_reset_done'), url(r'^resetpassword/$', password_reset, name='password_reset'), url(r'^reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>,+)/$', password_reset_confirm, name='password_reset_confirm'), url(r'^reset/done/$', password_reset_complete,name='password_reset_complete'), ] If I go like this then it gives error on this line of inbuilt function. reverse('password_reset') If I remove app_name = 'appname' then It works fine but namespacing is removed for other app functions. How can I resolve this ? -
Django cannot makemessages for djangojs
Currently I have this problem when trying to translate javascript files for Django. I have the url(r'^jsi18n/$', javascript_catalog, js_info_dict, name='javascript-catalog'), in urls.py and get that one in the template. This does not seem to be the issue to translating, when I run the django-admin.py makemessages command, it will throw some errors and I do not know why. $ django-admin.py makemessages -d djangojs -l nl_NL --keep-pot CommandError: errors happened while running msguniq /Users/../../src/locale/djangojs.pot:120: context separator <EOT> within string /Users/../../src/locale/djangojs.pot:121: context separator <EOT> within string msguniq: found 2 fatal errors This is what I find in the djangojs.pot file #: static/jsi18n/djangojs.js:38 static/jsi18n/djangojs.js:46 #: static/jsi18n/nl/djangojs.js:84 static/jsi18n/nl/djangojs.js:92 msgid " " msgid_plural "" msgstr[0] "" msgstr[1] "" When I delete these lines with empty string and run the command again, it will simply add them again after the command ran. Anyone had this issue before? -
Django Rest Framework token auth
I know this question has been answered before but the answer did not cover my confusion. So I have a view that checks if the user is correct with username and password- @api_view(['POST']) def example_view(request, format=None): username = request.data.get("username") password = request.data.get("password") content = {} try: user = User.objects.get(username=username) if user.check_password(password): content = {'user': unicode(user.username),'token': unicode(user.auth_token),} else: content = {'wrong password'} except User.DoesNotExist: content = { 'not registered', } return Response(content) I make a post request and return the token if the username and password is right. Now I made a model- class Check(models.Model): owner = models.ForeignKey(User,verbose_name = 'UserName') mood = models.TextField(null=True) And I have a function for the same model- @api_view(['GET']) def CheckApi(request): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) ?? query_set = Check.objects.get(owner= serializer = CheckSerializer(qs, many=True) return Response(serializer.data) And serializer for it- class CheckSerializer(serializers.ModelSerializer): class Meta: model = Check fields = ('__all__') What I basically want to do is after a user has been authenticated, I want the api to return data for that user rather than returning data for all of the users. -
results are not showing in taiga front end
I am working on customization of taiga project management system. I have code downloaded from github of taiga.io. I am making changes in below code: <pre>{{ user}}</pre> <div class="create-options"> <a href="#" ng-click="vm.newProject()" title="title" class="create-project-btn button-green"></a> <span tg-import-project-button="tg-import-project-button"> <a href="" title="title" class="button-blackish import-project-button"> <tg-svg svg-icon="icon-upload"></tg-svg> </a> <input type="file" class="import-file hidden"/> </span> </div> Data in {{user}} is: {"_attrs":{"full_name_display":"Administrator","id":4,"full_name":"Administrator","email":"admin@admin.com","is_active":true,} When I put condition ng-if="user.id==4" on div then it works fine but when I put condition ng-if="user.full_name=="Administrator"" on div it does not work. but value of {{user.full_name == "Administrator"}} is true. When I change condition to ng-if="user.full_name=='Administrator'" on div then it gives error: Uncaught Error: [$injector:modulerr] Failed to instantiate module taiga due to: Error: [$injector:modulerr] Failed to instantiate module templates due to: Error: [$injector:nomod] Module 'templates' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument. http://errors.angularjs.org/1.4.7/$injector/nomod?p0=templates at http://127.0.0.1:8000/v-1468840853868/js/libs.js:8:6745 at http://127.0.0.1:8000/v-1468840853868/js/libs.js:8:16302 at e (http://127.0.0.1:8000/v-1468840853868/js/libs.js:8:15775) at http://127.0.0.1:8000/v-1468840853868/js/libs.js:8:16087 at http://127.0.0.1:8000/v-1468840853868/js/libs.js:8:24768 at o (http://127.0.0.1:8000/v-1468840853868/js/libs.js:8:7152) at p (http://127.0.0.1:8000/v-1468840853868/js/libs.js:8:24616) at http://127.0.0.1:8000/v-1468840853868/js/libs.js:8:24785 at o (http://127.0.0.1:8000/v-1468840853868/js/libs.js:8:7152) at p (http://127.0.0.1:8000/v-1468840853868/js/libs.js:8:24616) at Qt (http://127.0.0.1:8000/v-1468840853868/js/libs.js:8:26306) at s (http://127.0.0.1:8000/v-1468840853868/js/libs.js:8:13829) at Object.at [as bootstrap] (http://127.0.0.1:8000/v-1468840853868/js/libs.js:8:14139) at Object.<anonymous> (http://127.0.0.1:8000/v-1468840853868/js/app-loader.js:1:1516) at Object.load (http://127.0.0.1:8000/v-1468840853868/js/libs.js:20:21097) at http://127.0.0.1:8000/v-1468840853868/js/libs.js:20:21149 http://errors.angularjs.org/1.4.7/$injector/modulerr?p0=templates&p1=Error%3A%20%5B%24injector%3Anomod%5D%20Module%20'templates'%20is%20not%20available!%20You%20either%20misspelled%20the%20module%20name%20or%20forgot%20to%20load%20it.%20If%20registering%20a%20module%20ensure%20that%20you%20specify%20the%20dependencies%20as%20the%20second%20argument.%0Ahttp%3A%2F%2Ferrors.angularjs.org%2F1.4.7%2F%24injector%2Fnomod%3Fp0%3Dtemplates%0A%20%20%20%20at%20http%3A%2F%2F127.0.0.1%3A8000%2Fv-1468840853868%2Fjs%2Flibs.js%3A8%3A6745%0A%20%20%20%20at%20http%3A%2F%2F127.0.0.1%3A8000%2Fv-1468840853868%2Fjs%2Flibs.js%3A8%3A16302%0A%20%20%20%20at%20e%20(http%3A%2F%2F127.0.0.1%3A8000%2Fv-1468840853868%2Fjs%2Flibs.js%3A8%3A15775)%0A%20%20%20%20at%20http%3A%2F%2F127.0.0.1%3A8000%2Fv-1468840853868%2Fjs%2Flibs.js%3A8%3A16087%0A%20%20%20%20at%20http%3A%2F%2F127.0.0.1%3A8000%2Fv-1468840853868%2Fjs%2Flibs.js%3A8%3A24768%0A%20%20%20%20at%20o%20(http%3A%2F%2F127.0.0.1%3A8000%2Fv-1468840853868%2Fjs%2Flibs.js%3A8%3A7152)%0A%20%20%20%20at%20p%20(http%3A%2F%2F127.0.0.1%3A8000%2Fv-1468840853868%2Fjs%2Flibs.js%3A8%3A24616)%0A%20%20%20%20at%20http%3A%2F%2F127.0.0.1%3A8000%2Fv-1468840853868%2Fjs%2Flibs.js%3A8%3A24785%0A%20%20%20%20at%20o%20(http%3A%2F%2F127.0.0.1%3A8000%2Fv-1468840853868%2Fjs%2Flibs.js%3A8%3A7152)%0A%20%20%20%20at%20p%20(http%3A%2F%2F127.0.0.1%3A8000%2Fv-1468840853868%2Fjs%2Flibs.js%3A8%3A24616)%0A%20%20%20%20at%20Qt%20(http%3A%2F%2F127.0.0.1%3A8000%2Fv-1468840853868%2Fjs%2Flibs.js%3A8%3A26306)%0A%20%20%20%20at%20s%20(http%3A%2F%2F127.0.0.1%3A8000%2Fv-1468840853868%2Fjs%2Flibs.js%3A8%3A13829)%0A%20%20%20%20at%20Object.at%20%5Bas%20bootstrap%5D%20(http%3A%2F%2F127.0.0.1%3A8000%2Fv-1468840853868%2Fjs%2Flibs.js%3A8%3A14139)%0A%20%20%20%20at%20Object.%3Canonymous%3E%20(http%3A%2F%2F127.0.0.1%3A8000%2Fv-1468840853868%2Fjs%2Fapp-loader.js%3A1%3A1516)%0A%20%20%20%20at%20Object.load%20(http%3A%2F%2F127.0.0.1%3A8000%2Fv-1468840853868%2Fjs%2Flibs.js%3A20%3A21097)%0A%20%20%20%20at%20http%3A%2F%2F127.0.0.1%3A8000%2Fv-1468840853868%2Fjs%2Flibs.js%3A20%3A21149 at http://127.0.0.1:8000/v-1468840853868/js/libs.js:8:6745 at http://127.0.0.1:8000/v-1468840853868/js/libs.js:8:25044 … -
django form wizard, ValidationError: ['ManagementForm data is missing or has been tampered.']
I'm using django wizard for a multiple form signup which in the end will be 4 or 5 pages of forms. However I'm getting validation errors that may relate to the form action somehow, which I'm not sure how to solve. The error seems to stem from line 282 here: https://github.com/django/django-formtools/blob/master/formtools/wizard/views.py but I'm not clear on what's causing it? (note I'm using django crispy forms but may not be relevant) views.py class SignupWizard(SessionWizardView): def get_template_names(self): return [TEMPLATES[self.steps.current]] def done(self, form_list, **kwargs): for form in form_list: if isinstance(form, SignupForm): user = form.save(self.request) complete_signup(self.request, user, settings.ACCOUNT_EMAIL_VERIFICATION, settings.LOGIN_REDIRECT_URL) else: other_signup_form = form.save(commit=False) user = self.request.user other_signup_form.user = user other_signup_form.save() return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL) signup_view = SignupWizard.as_view(SIGNUP_FORMS) forms.py class SignupForm(allauthforms.SignupForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.label_class = 'sr-only' self.helper.layout = Layout( Field('name', placeholder='Your Name'), PrependedText('email', '<i class="fa fa-envelope-o"></i>', placeholder="Your Email", autofocus=""), PrependedText('password1', '<i class="fa fa-key"></i>', placeholder="Enter Password"), Submit('sign_up', 'Sign up', css_class="btn btn-block btn-cta-primary"), ) class SignupForm2(forms.Form): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) template: {% block inner %} <h2 class="title text-center">Sign up now</h2> <p class="intro text-center">It only takes 2 minutes.</p> <div class="row"> {% crispy form %} </div> {% endblock %} -
How to delete objects from model periodically using Django and celery
Hi I am using celery in my django project which is basically a login registration app. I have configured celery in my project. I have got this code in my tasks.py from __future__ import absolute_import from celery import shared_task @shared_task def test_celery(): print 'hello worldd' It works fine when i try to do the above task. I can see the hello worldd printed in the console. But the actual job i need to do is, I check the ActivationCode model to see if the key_expires column is lesser than the current date and if it is i have to delete the user object from the user model. Below is my code from __future__ import absolute_import from celery import shared_task from django.contrib.auth.models import User from .models import ActivationCode import datetime @shared_task def remove_user(): inactive_users = [] activation_codes = ActivationCode.objects.all() for activation_code in activation_codes: if datetime.datetime.date(activation_code.key_expires) < datetime.datetime.date(datetime.datetime.now()): inactive_users.append(activation_code.user_id) User.objects.filter(id=inactive_users).delete() But this code does not work and celery stops here when i try to start the worker May I know where I am going wrong. ? -
How to chain a queryset together in Django correctly
Using the example below, I'm trying to use a queryset and append/chain filters together. To my understanding last queryset.count() should have just 1 instance, but it always had the original 10 in it. Expected output of last queryset.count() is 1: # Set a default queryset. def get_queryset(self, *args, **kwargs): queryset = super(UserMixin, self).get_queryset(*args, **kwargs) queryset.count() # 10 instacnes queryset.filter(id=1) queryset.count() # 10 instacnes excpeted 1 My thinking is that I need to re-save the query i.e. queryset = queryset.filter(id=1) Is this the correct way or there a way to chain them correctly? -
Fixture processed but not loaded
I created yaml fixture test.yaml: - model: myapp.person pk: 1 fields: email: test@example.com params: [] tests.py: class MyTests(TestCase): fixtures = ['test.yaml'] def test_1(self): # import pdb; pdb.set_trace() person = Person.objects.get(pk=1) The test result is Traceback (most recent call last): File "/home/django/myapp/tests.py", line 99, in test_part_count person = Person.objects.get(pk=1) File "/usr/lib/python3/dist-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/lib/python3/dist-packages/django/db/models/query.py", line 385, in get self.model._meta.object_name myapp.models.DoesNotExist: Person matching query does not exist. If I uncomment pdb.set_trace() and check Person.objects.all() got (Pdb) Person <class 'myapp.models.Person'> (Pdb) Person.objects.all() <QuerySet []> So i think, that fixtures doesn't fill the database. So I checked if fixture file is read. I changed params into paramz and got Traceback (most recent call last): File "/usr/lib/python3/dist-packages/django/db/models/options.py", line 617, in get_field return self.fields_map[field_name] KeyError: 'paramz' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/django/core/serializers/pyyaml.py", line 78, in Deserializer for obj in PythonDeserializer(yaml.load(stream, Loader=SafeLoader), **options): File "/usr/lib/python3/dist-packages/django/core/serializers/python.py", line 129, in Deserializer field = Model._meta.get_field(field_name) File "/usr/lib/python3/dist-packages/django/db/models/options.py", line 619, in get_field raise FieldDoesNotExist('%s has no field named %r' % (self.object_name, field_name)) django.core.exceptions.FieldDoesNotExist: Person has no field named 'paramz' During handling of the above exception, another exception occurred: Traceback (most recent call last): File … -
Select k random rows from postgres django ORM
We have a requirement, that we want to select k random rows from a database. So, our intial thought was going like this :- table.objects.filter(..).order_by('?')[:k] but then we read over the internet that this is highly inefficient solution so we came up with this (not so innovative):- random.sample(table.objects.filter(..), k) But this seems to be more slower than previous. So, we want to know what is correct approach for selection exactly k rows from the database, which in our case is postgres. -
mod_wsgi: Unable to stat Python home and ImportError: No module named 'encodings'
I am trying to construct a web site on Apache 2.4 using Django and mod_wsgi on Python 3.5.2. But when apache daemon httpd is started, following error message is output on /var/log/httpd/error_log. [Fri Sep 16 17:44:57.145900 2016] [wsgi:warn] [pid 20593] (13)Permission denied: mod_wsgi (pid=20593): Unable to stat Python home /home/ec2-user/.pyenv/versions/3.5.2. Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path. Fatal Python error: Py_Initialize: Unable to get the locale encoding ImportError: No module named 'encodings' So, I explored some article s about similar problems, e.g. Django + Apache + mod_wsgi permission denied mod_wsgi: ImportError: No module named 'encodings' but the causes of error message above are not yet resolved. Please indicate some points to be checked or documents to read and so on. My development environments are as follows. (1) Host and OS Hosting Service: Amazon AWS EC2 OS: Amazon Linux AMI release 2016.03 (2) Django Project I made Django project named testprj in the directory /home/ec2-user/django-sites with user account of ec2-user. [ec2-user@MyEC2 django-sites]$ pwd /home/ec2-user/django-sites [ec2-user@MyEC2 django-sites]$ ls -l total 4 drwxrwxr-x 3 ec2-user ec2-user 4096 Sep 16 14:50 testprj Database which the testprj uses is already … -
Upload multiple files using simple-salesforce python
I started learning SalesForce and develop app using django. I need assist for upload file to salesforce, For that I read simple-salesforce and this that help to upload file using rest and SOAP api. My question was how to upload one or more files using simple-salesforce? -
Django returns false for form.is_valid() when submitting through request module
I have a form in Django Application, which I am trying to submit through python request module. Every time I tried to submit a form through request module it says that form is not valid. form.is_valid() returns false in the django code. However, if I submit the same form manually using browser it's submitted successfully. I am using following code to submit the form session = requests.session() session.get("http://localhost:8000/autoflex/addresult/") csrf_token = session.cookies["csrftoken"] data = {"xml_url": xml_url, "csrfmiddlewaretoken": csrf_token} result = session.post("http://localhost:8000/autoflex/addresult/", data=data, headers={"Referer": "http://localhost:8000/autoflex/addresult/"}) -
Redirect to login when session cookie expires in Django
I'm trying to redirect to the login page when the cookie expires but it's not working. It's supposed to be as simple as adding these lines to settings.py: LOGIN_URL = '/login/' LOGIN_REDIRECT_URL='/login/' I'm using the decorator @login_required in my functions and I have tried @login_required(login_url='/login/') too. Urls are correctly set and when manually going to /login it works, so it's not an error in the path. When the session cookie expires and you try to access the app it gives you the error 'ViewDoesNotExist' (Could not import django.views.generic.simple.redirect_to. Parent module django.views.generic.simple does not exist.). -
Serving files from Django using mod_wsgi and apache on CentOS 6.8
I have a django web application which I need to serve from an apache server on CentOS 6.8. In order to get this, I´m using mod_wsgi. I have my project located in /path/to/myproject. Right there I have the following directories and files: - app1/ - db.sqlite3 - myproject/ - myprojectenv/ - manage.py - static/ I have added to my setting.py this directive: STATIC_ROOT = os.path.join(BASE_DIR, "static/") and I´ve tried to run the django server and I can see my app view correctly. So, after that I´ve tried to configure apache server in order to send a petition from my browser to my app, but apache rises a 403 Forbidden error. The steps that I followed are: - Add to httpd.conf the following information: <VirtualHost *:80> Alias /static /path/to/myproject/static Alias /app1 /path/to/myproject/app1 <Directory /path/to/myproject/static> Order allow,deny Allow from all </Directory> <Directory /path/to/myproject/app1> Order allow,deny Allow from all </Directory> <Directory /path/to/myproject/myproject> <Files wsgi.py> Order allow,deny Allow from all </Files> </Directory> WSGIDaemonProcess myproject user=myuser group=mygroup python-path=/path/to/myproject:/path/to/myproject/myprojectenv/lib/python2.7/site-packages WSGIProcessGroup myproject WSGIScriptAlias / /path/to/myproject/myproject/wsgi.py </VirtualHost> Then, I gave rights to apache user, in order to allow apache to have access to my django project: - sudo usermod -a -G myuser apache - chmod 710 /home/myuser - … -
Template syntax error when rendering crispy-form
I use semantic-ui as template for crispy-forms. When trying to load the page it results in the following error: TemplateSyntaxError at /forum/newpost/pqs53kqsbgsqd66pg0i60u-isjtvagbo4ii4q9/ crispy tag's template_pack argument should be in ('bootstrap', 'uni_form', 'bootstrap3', 'foundation-5') Settings file contains entries below (among others): CRISPY_TEMPLATE_PACK = 'semantic-ui' INSTALLED_APPS = ('crispy_forms', 'semantic_ui') Here is the template code from forumpost_create.html: {% extends 'forum/layouts/forum_main.html' %} {% load crispy_forms_tags %} {% block content %} <div class="ui main text container"> <form action="" method="post" class="ui form"> {% csrf_token %} {% crispy form %} <input type="submit" value="Save" /> </form> </div> {% endblock %} The error disappears when I use form|crispy in the template, but then the template is rendered unaffected, even when looking at the output HTML source, no changes whatsoever. Code from forms.py class ForumPostForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ForumPostForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.layout = Layout( Fieldset( 'Post body', 'body' ), ButtonHolder( Submit('submit', 'Submit', css_class='ui primary button') ) ) class Meta: model = ForumPost fields = ['body'] How to make this to work? Is it because I am using semantic-ui and something needs to be done differently? (Majority of the tutorials I encounter prefer bootstrap). -
Best way to define Django global variable on apache starup
I have some configuration in a json file and I want to load those configuration on Django startup (Apache server startup).. I will be using those global variable within all the application. For Example: External server connection api or number of instances. What is the best way to define the global variables. I want to load the json file when server starts and use the variable value util server stop. ?