Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Print Dates range if they are available in Database
from below code i am going to print date ranges that's fine but what the problem is i need to print the date ranges , those available in database only [this image shows the created_at date field which is in look model . I need these dated to be printed if user select the date rage between dec 1 to dec 30 ]1 while (current_date >= from_date): r = r + 1 ws.write(0,r,current_date,style) current_date -= timedelta(days = 1) -
500 Internal Server Error: Python 3.5, Django and mod_wsgi
I'm trying to deploy a Python/Django application on DigitalOcean and getting the following error: apache error.log [wsgi:error] [pid 17060] from django.core.wsgi import get_wsgi_application [wsgi:error] [pid 17060] ImportError: No module named 'django' [wsgi:error] [pid 17060] mod_wsgi (pid=17060): Target WSGI script '/var/www/demo-app/src/demo/demo/wsgi.py' cannot be loaded as Python module. [wsgi:error] [pid 17060] mod_wsgi (pid=17060): Exception occurred processing WSGI script '/var/www/demo-app/src/demo/demo/wsgi.py'. [wsgi:error] [pid 17060] Traceback (most recent call last): [wsgi:error] [pid 17060] File "/var/www/demo-app/src/demo/demo/wsgi.py", line 12, in <module> [wsgi:error] [pid 17060] from django.core.wsgi import get_wsgi_application [wsgi:error] [pid 17060] ImportError: No module named 'django' [wsgi:error] [pid 17060] mod_wsgi (pid=17060): Target WSGI script '/var/www/demo-app/src/demo/demo/wsgi.py' cannot be loaded as Python module. [wsgi:error] [pid 17060] mod_wsgi (pid=17060): Exception occurred processing WSGI script '/var/www/demo-app/src/demo/demo/wsgi.py'. [wsgi:error] [pid 17060] Traceback (most recent call last): [wsgi:error] [pid 17060] File "/var/www/demo-app/src/demo/demo/wsgi.py", line 12, in <module> [wsgi:error] [pid 17060] from django.core.wsgi import get_wsgi_application [wsgi:error] [pid 17060] ImportError: No module named 'django' My setup is as follows: Ubuntu==16.04 django==1.11.4 apache==2.4.18 mod-wsgi==4.5.22 python 3.5(virtualenv) libapache2-mod-wsgi-py3 Any ideas on what I'm missing? -
Providing a initial list for related_name field cannot be accessed
Models (Employee has a foreign key to Company with related_name employees): class Company(models.Model): name = models.CharField(max_length=255) address = models.CharField(max_length=1023) class Employee(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='employees') name = models.CharField(max_length=255) staffId = models.IntegerField() active = models.BooleanField(default=False) View: class CompanyForm(CreateView): model = Company fields = '__all__' template_name = 'forms/company_form.html' def get_initial(self): initial = super(CompanyForm, self).get_initial() initial['employees'] = [Employee(name='Ann', staffId=10, active=True), Employee(name='John', staffId=2, active=False)] return initial Template: <head> </head> <body> <form id="myForm" method="post"> {% csrf_token %} {{ form.as_p }} {% for employee in form.employees %} <p>{{ employee.name }}</p> {% endfor %} <input type="submit" value="Save"> </form> </body> And this is what I see rendered: I expected to see the two names of the Employee objects I passed in get_initial method. Why doesn't this work and what can I do to get it working? -
EDITGetting error main() takes 2 positional arguments but 3 were given
I am testing out google adwords api features (NOTE: This question isnt direactly aimed at Google Ad Words API). I am facing an error that says : main() takes 2 positional arguments but 3 were given Heres what I have done: 1) Created a Keyword model that has a keyword charfield 2) Created a KeywordForm that has a form element of type CharField 3) Used the form in a html page to get the keyword through the POST method 4) After the POST, the url is routed to a view keyword_add which sets two values namely adwords_client = adwords.AdWordsClient.LoadFromStorage() ad_group_id = 'XXXXXXXXX ' .Also it gets the value of keyword model using new_keyword = Keyword.objects.all() . It then calls a function located in a python script using the function call ad_group_update.main(adwords_client, ad_group_id, new_keyword) 5) The function main in the python script add_keywords is executed using the three arguments adwords_client, ad_group_id & new_keyword The following error arises when i do this : 1) error while executing main() Apart from this error I have another question in the code: from googleads import adwords AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' def main(client, ad_group_id, keyword): # Initialize appropriate service. ad_group_criterion_service = client.GetService( 'AdGroupCriterionService', version='v201710') # Construct keyword … -
Passing Parameters to upload_to Parameter in Django File Upload
I am using the following post to upload files in Django: https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html. In the post, it mentions that the upload_to parameter can be a callable that returns a string. In the example provided, the callable accepts two parameters, instance and filename as follows: def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'user_{0}/{1}'.format(instance.user.id, filename) class MyModel(models.Model): upload = models.FileField(upload_to=user_directory_path) At what point and how do I pass parameters to upload_to? I am using form.save(commit=True) to persist form values to the database. Any help would be appreciated. Thanks. -
Django Rest Framework: Derived model serializer fields
I'm working on building a tree-like hierarchical database system using Django Rest Framework and django-polymorphic-tree. I have two models- BaseTreeNode and DescriptionNode (the later one is derived from BaseTreeNode). Specifically, here's my models.py: class BaseTreeNode(PolymorphicMPTTModel): parent = PolymorphicTreeForeignKey('self', blank=True, null=True, related_name='children', verbose_name=_('parent')) title = models.CharField(_("Title"), max_length=200) def __str__(self): return "{}>{}".format(self.parent, self.title) class Meta(PolymorphicMPTTModel.Meta): verbose_name = _("Tree node") verbose_name_plural = _("Tree nodes") # Derived model for the tree node: class DescriptionNode(BaseTreeNode): description = models.CharField(_("Description"), max_length=200) class Meta: verbose_name = _("Description node") verbose_name_plural = _("Description nodes") So, each title field (belonging to BaseTreeNode) has an associated description field (belonging to DescriptionNode) with it. Now, all I want to have is a JSON that returns a nested representation of my entire tree. For now, I have only defined a simple serializer with a recursive field. My serializers.py from rest_framework_recursive.fields import RecursiveField class DescriptionNodeSerializer(serializers.ModelSerializer): class Meta: model = DescriptionNode fields = ('description',) class BaseTreeNodeSerializer(serializers.ModelSerializer): subcategories = serializers.ListSerializer(source="children",child=RecursiveField()) class Meta: model = BaseTreeNode fields = ('id', 'title', 'subcategories') Which gives me (for BaseTreeNodeSerializer only): [ { "id": 1, "title": "Apple", "subcategories": [ { "id": 2, "title": "Contact Person", "subcategories": [] }, { "id": 3, "title": "Sales Stage", "subcategories": [ { "id": 4, "title": "Suspecting", "subcategories": … -
Get the dates for the created date only
models.py class UserWay(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateField() updated_at = models.DateTimeField(auto_now=True) class Grades(models.Model,): user_ql = models.OneToOneField(UserQuickLook, related_name = "grades_ql") health = models.CharField() overall = models.FloatField() views.py to_date = request.GET.get('to_date',None) from_date = request.GET.get('from_date', None) while to_date >= from_date: r = r + 1 ws.write(0,r,current_date,style) to_date -= timedelta(days = 1) user will fill the form daily that form is going to store. my problem is need to show the dates from date range of filled form . per one day only once it is going to filled -
Unable to fetch list value - django
my posted data looks like this : QueryDict: {u'question': [u'how to'], u'submit': [u'submit'], u'tag_name': [u'one', u'two'], u'csrfmiddlewaretoken': [u'WtOIVwdti7pBaT9LwyYtReS2WEoRpXVJXXLqCDgHaZi14OMmSXkE8g7ccTVTJ48h'], u'ansc': [u'multi'], u'options': [u'3']} I'm trying to fetch 'tag_name' data, but each time I do request.POST.get('tag_name') all i get is two I'm not able to fetch entire list, even after looping entire request object. How to fetch this object ? -
How to replace the key name in Serializer?
I have a ModelSerializer: class PublicNetwokSerializer(ModelSerializer): """ PublicNetwok """ class Meta: model = PublicNetwok fields = "__all__" The model is bellow: class PublicNetwok(models.Model): name = models.CharField(max_length=12) desc = models.CharField(max_length=24) ... You know if I use the ModelSerializer I will get all the key-values like bellow: [ { "name":"xxx", "desc":"xxx", }, { "name":"xxx", "desc":"xxx", } ] But I want to change the key desc to description, in Django-Rest-Framework how to access that? -
Django Rest Framework: Could not resolve URL for hyperlinked relationship using view name "post-detail"
I found a lot of answers to the similar issue, but none of them helped me. I am new to the backend and Django, I already spend a few days trying figure out what I am doing wrong, but no success. You guys my lest hope, cause I don't know what to try more... I would appreciate the help a lot! So, when I call http://127.0.0.1:8000/users/{user_name}/ I am getting : ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "post-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. If I change HyperlinkedRelatedField on any other field it's working properly... urls.py app_name = 'api' urlpatterns = [ url(r'^posts/(?P<post_id>\d+)/$', PostDetails.as_view(), name='post-detail'), url(r'^users/(?P<username>[\w\-]+)/$', UserPosts.as_view()), ] views.py class PostDetails(APIView): """ - GET a post """ def get(self, request, post_id): post = Post.objects.get(id=post_id) post_serializer = PostSerializer(post) return Response(post_serializer.data) class UserPosts(APIView): """ GET all user posts """ def get(self, request, username): user = User.objects.get(username=username) serializer = UserSerializer(user, context={'request': request}) return Response(serializer.data) serializer.py class UserSerializer(serializers.ModelSerializer): posts = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='post-detail', lookup_field='id') # Mandatory for UUID serialization user_id = serializers.UUIDField() class Meta: model = User exclude = ('id', 'password') read_only_fields = ('created', 'username', … -
Display different div element components when Toggle switch slider
// I want to have a toggle switch which if slide left a div content components pops up and on slide right a different div content pop up.How can I proceed? HTML CONTENT <form> <label class="switch"> <input type="checkbox" checked="true" > <div class="slider round"></div> </label> </form> <div id ="menu1"> Menu 1 conetnt </div> <div id ="menu2"> MEnu 2 content </div> CSS CONETENT /* The switch - the box around the slider */ .switch { position: relative; display: inline-block; width: 60px; height: 34px; } /* Hide default HTML checkbox */ .switch input {display:none;} /* The slider */ .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; -webkit-transition: .4s; transition: .4s; } .slider:before { position: absolute; content: ""; height: 26px; width: 26px; left: 4px; bottom: 4px; background-color: white; -webkit-transition: .4s; transition: .4s; } input:checked + .slider { background-color: #2196F3; } input:focus + .slider { box-shadow: 0 0 1px #2196F3; } input:checked + .slider:before { -webkit-transform: translateX(26px); -ms-transform: translateX(26px); transform: translateX(26px); } /* Rounded sliders */ .slider.round { border-radius: 34px; } .slider.round:before { border-radius: 50%; } /* STRUCTURE //As you can see I want like if the toggle slides right content of div id="menu1" to be displayed … -
Django JWT HTTP Authorization not passing
I am trying to use JWT token authentication with Django rest framework. I was able to successfully get the access and refresh token. And I made sure that the token is valid. But when I try to access some protected apiview with the access token. It says {"detail":"Authentication credentials were not provided."}. curl -H "Authorization: JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTE0MzQzNzcxLCJqdGkiOiIwYmE5YTcxZTJmMzQ0YmRmOTM1ZWQ3MTU3ZmI2NDkyZiIsInVzZXJfaWQiOjh9.dI3t8yvNe2Z7MKXojGvFpq_Etf1cLg8QSYsNobJ6jQ0" http://localhost:8000/users/me/ However, on server side I did get the request.META with a HTTP_AUTHORIZAITON field that contains the above token. I'm currently developing on localhost instead of Apache, with following files and configurations: In views.py: class GetMyInfo(views.APIView): def get(self,request): print(request.META) user = request.user profile = user.profile profile_serializer = ProfileSerializer(instance = profile) return Response(profile_serializer.data, status = HTTP_200_OK) In url.py: urlpatterns = [ re_path(r'^admin/', admin.site.urls), re_path(r'^api/$', get_schema_view()), re_path(r'^api/auth/', include('rest_framework.urls')), re_path(r'^api/auth/token/obtain/$', TokenObtainPairView.as_view(), name = 'token_obtain_pair'), re_path(r'^api/auth/token/refresh/$', TokenRefreshView.as_view(), name = 'token_refresh'), re_path(r'^api/auth/token/verify/$', TokenVerifyView.as_view(), name = 'token_verify'), #re_path(r'^api-token-auth/', authviews.obtain_auth_token, name = 'obtain_auth_token'), re_path(r'^users/$', views.CreateUser.as_view(), name = 'register'), re_path(r'users/(?P<uuid>[0-9a-f-]+)/$', views.GetUserInfo.as_view(), name = 'info'), re_path(r'users/me/$', views.GetMyInfo.as_view(), name = 'myinfo'), ] settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'api' ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES':( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES':( 'rest_framework_simplejwt.authentication.JWTAuthentication', #'rest_framework.authentication.SessionAuthentication', #'rest_framework.authentication.TokenAuthentication', #'rest_framework.authentication.BasicAuthentication', ), 'TEST_REQUEST_DEFAULT_FORMAT': 'json', } AUTH_USER_MODEL = 'api.User' In models.py: @receiver(post_save, sender = settings.AUTH_USER_MODEL) def create_auth_token(sender, instance = … -
Django-Paypal using the signals to create Order History
I'm using the django-paypal on my django website project, everything is working good, the payment is working and i'm getting to signals back to my website. After testing it a bit, I can see the signals registered at the admin page under Paypal IPN. I'm try to make a page that only the admin user can see, with all the orders that have been made, for example "{user] paid 20$ for {name} at {date.time}" any tips and help would be awesome !!! -
How can i implement EAV in django?
I am extremely new to Django and I am trying to implement EAV within my application. I cannot find any examples of how to do this so would anyone mind posting a quick random example of how it would be programmed? Thanks! -
Django rest framework custom response message for different validation
So i want to create custom message for the different fail based on the serializer validation. But i was only able to find how to create a standard custom response for success and fail only. Though the only response i want to create is for the failed prompt message. i found one of the post but its not really what i wanted for the error code source : Django Rest Framework custom response message Basically the error message must be based on the specific validation error in serializer.py Here is my code serializer.py class UserCreate2Serializer(ModelSerializer): email = EmailField(label='Email Address') valid_time_formats = ['%H:%M', '%I:%M%p', '%I:%M %p'] birthTime = serializers.TimeField(format='%I:%M %p', input_formats=valid_time_formats, allow_null=True, required=False) class Meta: model = MyUser fields = ['username', 'password', 'email', 'first_name', 'last_name', 'gender', 'nric', 'birthday', 'birthTime', 'ethnicGroup'] extra_kwargs = {"password": {"write_only": True}} def validate(self, data): # to validate if the user have been used email = data['email'] user_queryset = MyUser.objects.filter(email=email) if user_queryset.exists(): raise ValidationError("This user has already registered.") return data # Custom create function def create(self, validated_data): username = validated_data['username'] password = validated_data['password'] email = validated_data['email'] first_name = validated_data['first_name'] last_name = validated_data['last_name'] gender = validated_data['gender'] nric = validated_data['nric'] birthday = validated_data['birthday'] birthTime = validated_data['birthTime'] ethnicGroup = validated_data['ethnicGroup'] user_obj … -
Iterate over two django querysets where objects have a field in common
I have a TradingDay model that store stock market price data for single stock on a given day. What I would like to be able to do is take two different stocks, and iterate over every date that the two stocks have in common (I might be missing data, some stocks are newer than others, etc.) so that I can compare their performance. I know I could just create two querysets and handle the logic of pairing up the different stock objects in python, but this seems like an inefficient use of the database. Does django have any built in functionality to accomplish something like this? Thanks! class TradingDay(models.Model): stock = models.ForeignKey('Stock', on_delete=models.CASCADE) date = models.DateField() close_price = models.DecimalField(max_digits=8, decimal_places=2) -
Super easy tutorial throwing django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
I created a simple django web app. When I run the models.py file I get the following error. I've tried a number of solutions including taking out my apps one by one, reinstalling django (I have version 2.0) doing an 'ol system restart, inserting import django + django.setup(), refreshing the virtualenv. Traceback (most recent call last): File "C:/Users/Pritee/djangogirls/blog/models.py", line 6, in <module> class Post(models.Model): File "C:\Users\Pritee\djangogirls\myvenv\lib\site- packages\django\db\models\base.py", line 100, in __new__ app_config = apps.get_containing_app_config(module) File "C:\Users\Pritee\djangogirls\myvenv\lib\site- packages\django\apps\registry.py", line 244, in get_containing_app_config self.check_apps_ready() File "C:\Users\Pritee\djangogirls\myvenv\lib\site- packages\django\apps\registry.py", line 127, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Models.py from django.db import models from django.utils import timezone class Post(models.Model): author = models.ForeignKey('auth.User',on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title Settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'iua)_567ww!*c9#dhg#f&u4ft$(47!cz@98!$ro=^+u!+t' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['127.0.0.1'] # Application definition INSTALLED_APPS … -
Strengthen password in change password page - django-allauth
I'm using django-allauth I can't find any mechanism to restrict any character in the change password page. Minimum 8 Characters At least 1 uppercase and lowercase letter At least 1 number -
Django 1.11 One-to-Many relationship no related set
So I have two models: class UserData(models.Model): """ Holds basic user data. """ id = models.IntegerField(primary_key=True, editable=False) # id is taken from data. class ConsumptionTimePoint(models.Model): """ Individual consumption time points with a One-to-Many relationship with UserData """ user_data = models.ForeignKey(UserData, on_delete=models.CASCADE) And when I try and test them by creating them both, and their relationship in a test: def test_basic_model_creation(self): user_data_object = UserData.objects.create(id=1) user_data_object.save() consumption_time_point_object = ConsumptionTimePoint.objects.create(user_data=user_data_object) consumption_time_point_object.save() self.assertIsNotNone(consumption_time_point_object.user_data) self.assertEquals(1, len(user_data_object.consumption_time_point_set.all())) I get the following error: AttributeError: 'UserData' object has no attribute 'consumption_time_point_set' But from my understanding that's the correct way to get the set. Have I misnamed something? Or is this a testing issue? -
sort by a value in Pandas column
I groupby my data as follows in Pandas: df.groupby(by=['industry', 'country', 'category'])['category'].count() The DataFrame looks something like this after the groupby: --------------------------------------- Industry | Country | category | --------------------------------------- Oil | Portugal | 0 | 14 1 | 4 None | 7 Germany | 1 | 27 0 | 22 None | 7 Spain | 1 | 12 0 | 1 --------------------------------------- Gas | Ireland | 1 | 2 0 | 11 None | 1 Italy | 0 | 120 1 | 33 Malta | 1 | 3 0 | 4 None | 7 Turkey | 0 | 355 1 | 44 --------------------------------------- However, I would like to sort my data based on the count of a particular Category value. For example, sort it by the count of category value '0' so that the frame looks like below. Please note the sorting based on the count of category '0' (22,14,1) and (355,120,11,4). --------------------------------------- Industry | Country | category | --------------------------------------- Oil | Germany | 1 | 27 0 | 22 None | 7 Portugal | 0 | 14 1 | 4 None | 7 Spain | 1 | 12 0 | 1 --------------------------------------- Gas | Turkey | 0 | 355 1 … -
How to ensure no repeating datas when use django?
background I aim at overing a project which is made up of django and celery. And I code two tasks which would sipder from two differnt web and save some data to database —— mysql. As before, I do just one task, and I use update_or_create shows enough. But when I want to do more task in different workers ,and all of them may save data to database, and what's more, they may save the same data at the same time. question How can I ensure different tasks running in different worker makeing no repeating data when all of them try to save the same data? I know a django API is select_for_update which would set a lock in database. But when I reading the documentions, it similar means, would select,if exist,update. But I want to select,if exist,update,else create. It would more be like update_or_create,but this API may not use a lock? -
Django ManagementForm data is missing or has been tampered error on request.POST
When i pass request.POST parameter to my CargoUnitFormSet. It get this error in command line. File "C:\Python27\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django\forms\formsets.py", line 98, in management_form code='missing_management_form', ValidationError: [u'ManagementForm data is missing or has been tampered with'] In myform i create a formset. And my formset is displayed on my web page. Whenever i pass request.POST as a parameter to save my formset it gives this validation error. Here is my view function: def create_entity(request): from django.forms import BaseFormSet from django.forms import formset_factory from django.forms.models import modelformset_factory, BaseModelFormSet CargoUnitFormSet = formset_factory(CargoUnitForm,max_num=3) data = dict() if request.method == 'POST': cargo_form = CargoForm() cargo_form = CargoForm(request.POST, request.FILES or None) cargo_unit_formset = CargoUnitFormSet(request.POST,prefix="foo") if not cargo_form.is_valid(): form = CargoForm() data['form_is_valid'] = False if cargo_form.is_valid() and cargo_unit_formset.is_valid(): cargo = cargo_form.save() for form in cargo_unit_formset.forms: cargo_unit = form.save(commit=False) cargo_unit.list = cargo cargo_unit.save() data['form_is_valid'] = True context = { 'form': cargo_form, 'formset':cargo_unit_formset } data['html_form'] = render_to_string("cargos/form-create.html", context, request=request) return JsonResponse(data) Here is my related html template for formset <div class="row"> {{formset.management_formset}} {% for form in formset.forms %} <div class="item well"> {{ form.as_p }} <p><a class="delete btn btn-danger" href="#"><i class="icon-trash icon-white"></i> Delete</a></p> </div> {% endfor %} </div> Thanks in advance. -
Celery in Django Matching Query Does Not Exist even though Model is present
I'm currently moving from my dev environment to my AWS server and I've hit a snag regarding Celery. These issues where not present when running in the dev environment but have now popped up in the server. Its claims that my AutomationSettings model doesn't exist but its present and the import instructions are present. I've checked out here, here, here and here. How do I fix? Trace (.venv) ubuntu@ip-172-31-43-50:~$ celery -A milingual worker -l info Traceback (most recent call last): File "/home/ubuntu/.venv/bin/celery", line 11, in <module> sys.exit(main()) File "/home/ubuntu/.venv/local/lib/python2.7/site-packages/celery/__main__.py", line 14, in main _main() File "/home/ubuntu/.venv/local/lib/python2.7/site-packages/celery/bin/celery.py", line 326, in main cmd.execute_from_commandline(argv) File "/home/ubuntu/.venv/local/lib/python2.7/site-packages/celery/bin/celery.py", line 488, in execute_from_commandline super(CeleryCommand, self).execute_from_commandline(argv))) File "/home/ubuntu/.venv/local/lib/python2.7/site-packages/celery/bin/base.py", line 281, in execute_from_commandline return self.handle_argv(self.prog_name, argv[1:]) File "/home/ubuntu/.venv/local/lib/python2.7/site-packages/celery/bin/celery.py", line 480, in handle_argv return self.execute(command, argv) File "/home/ubuntu/.venv/local/lib/python2.7/site-packages/celery/bin/celery.py", line 412, in execute ).run_from_argv(self.prog_name, argv[1:], command=argv[0]) File "/home/ubuntu/.venv/local/lib/python2.7/site-packages/celery/bin/worker.py", line 221, in run_from_argv return self(*args, **options) File "/home/ubuntu/.venv/local/lib/python2.7/site-packages/celery/bin/base.py", line 244, in __call__ ret = self.run(*args, **kwargs) File "/home/ubuntu/.venv/local/lib/python2.7/site-packages/celery/bin/worker.py", line 255, in run **kwargs) File "/home/ubuntu/.venv/local/lib/python2.7/site-packages/celery/worker/worker.py", line 94, in __init__ self.app.loader.init_worker() File "/home/ubuntu/.venv/local/lib/python2.7/site-packages/celery/loaders/base.py", line 116, in init_worker self.import_default_modules() File "/home/ubuntu/.venv/local/lib/python2.7/site-packages/celery/loaders/base.py", line 111, in import_default_modules return [self.import_task_module(m) for m in self.default_modules] File "/home/ubuntu/.venv/local/lib/python2.7/site-packages/celery/loaders/base.py", line 97, in import_task_module return self.import_from_cwd(module) File "/home/ubuntu/.venv/local/lib/python2.7/site-packages/celery/loaders/base.py", line 106, … -
Make google recaptcha not to ask more than once
views.py def the_same_page(request): #This POST request is from '/the_same_page/' if request.method == 'POST': if some_check(): return render(request, 'the_same_page.html') #something goes wrong so I will make render the same page, the same url. the_same_page.html <div class="form-group"> <label class="control-label" for="">text</label> {{ form.text }} </div> <div class="g-recaptcha" data-sitekey="121~~~~1212"></div> <button class="btn btn-default" type="submit">Submit</button> The user want to submit any text, the user have to do recaptcha again and again. I want to remove this recaptcha re-check. How can I set recaptcha to state of human_verified? So don't ask again if the user have checked this recaptcha before? -
Convert a one-to-many hierarchy of Models to a plain json in Django
I have a chain of Django Models with one-to-many relation between one and another. For example class Country(models.Model): name = models.CharField(max_length=128) code = models.IntegerField(unique=True) class Manufacturer(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) address = models.CharField(max_length=128) class Car(models.Model): manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE) color = models.CharField(max_length=32) I want to make a dump of the database as a plain json, i.e. an array of objects with no sub-objects. For example { "cars": [ { "color": "white", "manufacturer_address": "ave 1", "manufacturer_country_name": "the uk", "manufacturer_country_code": "56" }, { "color": "red", "manufacturer_address": "ave 2", "manufacturer_country_name": "the usa", "manufacturer_country_code": "57" } ] } Without a doubt, I can hard code all the foreign keys used. It's what I've come up with so far, a sequence of calls to django.forms.models.model_to_dict and models.XXX.objects.filter(id=XXX). But is there a more idiomatic (shipped with Python or Django) way to achieve that? To introspect a Car class and add all its ordinary (non-FK) fields to a json detect all its FKs, "inflate" them recursively as it is stated in item 1