Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Django Saving new record, int() argument must be a string or a number, not 'QueryDict'
I'm using Django 1.11 and Python 2.7.13. I'm deploying on Google App Engine using Cloud SQL (MySQL 5.7) but the error happens in my local development environment. I have a very simple app with 1 form that collects some data and tries to save it as a new record in the database. It works fine if I use the default form and CreateView like this: # views.py class SubjectCreate(CreateView): model = Subject fields = '__all__' success_url = reverse_lazy('subapp:index') However, I want to customize the form (move fields around, use check boxes, etc.) To do this from what I can tell I can't use the default CreateView, etc. but have to write my own. So here's what I've done: # models.py class Subject(models.Model): subject_date = models.DateTimeField(default=timezone.now) subject_field2 = models.CharField(max_length=20) ... whole bunch of other fields ... def __str__(self): return self.subject_date.strftime('%Y-%m-%d %H:%M') + self.subject_field2[:35] + "..." #views.py def createnewsubject(request): if request.method == 'POST': subject_form = NewSubjectForm(request.POST) if subject_form.is_valid(): subject_data = Subject(request.POST) subject_data.save() return HttpResponseRedirect('/') else: subject_form = NewSubjectForm() return render(request, 'subapp/subject_form.html', {'form': consultation_form}) # forms.py class NewSubjectForm(forms.ModelForm): class Meta: model = Consultation fields = "__all__" When the code hits subject_data.save() I get TypeError at /new/ int() argument must be a string or … -
KeyError: 'region' query set
I'm using this code to get a query set with 3 values (game id, platform and release date). It works for the first few json objects until it reaches a certaine one it returns this error: KeyError: 'region' and the cause is region=release_date_object['region'] # Get from 'release_date_object' (JSON object) release_date = ReleaseDate.objects.filter(game=game.id, platform=release_date_object['platform'], region=release_date_object['region']) -
API Integration in Django
I am trying to use the OpenDOTA API in my pet project. At the moment, I am having problem displaying the content of the API into my CBV. My views.py: from django.views.generic import TemplateView import requests import json # Create your views here. class HeroList(TemplateView): template_name = 'dota/heroes.html' url = 'https://api.opendota.com/api/heroes' r = requests.get(url) r.text result = r.json() I am lost on how to call the json in my HTML. I've tried running the same code in python IDLE, and when I type the "result" and hit enter, it gives my the dict. Any idea on how should I display the dict into my template? -
How to create two records in database at once with one form in Django 1.11
Here are my two models: class User_Phrase(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) start_date = models.DateTimeField(default=datetime.now, editable=True) interval_in_sec = models.IntegerField() class Phrase(models.Model): phrase = models.CharField(max_length=250, primary_key=True) user_phrase_id = models.ForeignKey(User_Phrase, on_delete=models.CASCADE) I want to create two records in the database with one form. Scenario: User wants to fill the fields start_date, name, phrase, interval_in_sec. When user submits the form firstly it takes the value from phrase field checks if the current phrase is already stored in the Phrase if yes it binds the user_phrase record to that phrase else it creates phrase record and then associates it with the user_phrase Also, I am using this a string for the phrase primary key, I am not sure if that is correct design but I want unique phrases to be stored in that table. The purpose of that table is basically when a user looks for a phrase, I want to store it and to store some other values connected to that phrase. How do I achieve that?