Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Remove some logs in gunicorn
Hi I am using gunicorn as a web server for django. I would like the Closing connection log to be excluded or at least somewhat avoided.. Is that possible? [2018-11-22 19:07:31 +0800] [11] [DEBUG] GET /admin/login/ {Client-IP: -, Request-time: 0.010543, Request-date: [22/Nov/2018:19:07:31 +0800], HTTP-Status: "GET /admin/login/ HTTP/1.1", HTTP-Status-Code: 200, Response-length: 1987, Http-Referrer: -, User-Agent: kube-probe/1.9+} [2018-11-22 19:07:31 +0800] [11] [DEBUG] Closing connection. -
nginx gunicorn with docker: how to use multiple dockerfiles
I'm using the following example to build a django-postgres-nginx-gunicorn web server. I'd like to have separated folders for each container. The following structure of the project works correctly. The main Dockerfile is used for the hello app (the django project): svm3_03 |____Dockerfile |____config | |____gunicorn | | |____conf.py | |____nginx | | |____conf.d | | |____local.conf | |____db | |____db_env |____docker | |__db | |__Dockerfile | |__dataForDB |__docker-compose.yml |__hello the docker-compose.yml looks like this: version: '3' ... services: djangoapp: build: context: . ... and the Dockerfile has the following line: CMD ["gunicorn", "-c", "config/gunicorn/conf.py", "--bind", ":8000", "--chdir", "hello", "hello.wsgi:application"] Everything works. Now I tried to have the same structure as the DB image also for the django app so I move the main Dockerfile and the hello directory inside the docker folder... I created a new folder inside the docker folder with name djangoapp and I moved there the Dockerfile and the hello folder. The new structure is the following: svm3_03 |____config | |____gunicorn | | |____conf.py | |____nginx | | |____conf.d | | |____local.conf | |____db | |____db_env |____docker | |__db | | |__Dockerfile | | |__dataForDB | |__djangoapp | |__Dockerfile | |__hello |__docker-compose.yml All I did then was … -
Exporting django variable to python file
Hi everybody and thank you in advance for your help. I want to introduce a number in my home.html, save it as variable 'n' and export it to my_calculations.py file. <form> <label for='number'>Number:</label> <input type='number' value='Save'> <button type="submit">submit</button> </form> Can you please explain me what should I exactly do? I look everywhere but there's a lot of info about how to send a variable from .py to templates but not the other way round. -
django : form_valid() missing 1 required positional argument: 'form'
I'm wondering how I can solve this issue in my form_valid() function : form_valid() missing 1 required positional argument: 'form' I'm using Django Class Based View and formsets. But, it could be possible to get IntegrityError and I added a try/except in order to save the formset when forms are valid, and redirect the template with an error message when I get this issue. class AnimalCreateView(CreateView): model = Animal template_name = 'animal_form.html' def get_context_data(self, **kwargs): context = super(AnimalCreateView, self).get_context_data(**kwargs) foo_queryset = Foo.objects.all() context['FooFormSets'] = FooFormSet(self.request.POST or None, self.request.FILES or None, prefix='foo', queryset=foo_queryset) return context def form_valid(self, request, form): context = self.get_context_data() formsets = context['FooFormSets'] if form.is_valid(): self.object = form.save() try: if formsets.is_valid(): formsets.instance = self.object formsets.save(commit=False) for element in formsets: element.save(commit=False) formsets.save() except IntegrityError: messages.error(self.request, _(f"Issue with foo")) return render(request, self.template_name) return super(AnimalCreateView, self).form_valid(form) I would like to know what I have to do in my form_valid() function in order to solve my issue and redirect user on the same template form with error message. Thank you -
Add fields dynamically in django ModelForm
my model class MyModel(models.Model): remark = models.CharField(max_length=120) data_1 = models.BooleanField(default=False) data_2 = models.BooleanField(default=False) data_3 = models.BooleanField(default=False) data_4 = models.BooleanField(default=False) Form class MyModelForm(forms.ModelForm): CHOICES= (("data_1", "data_1"), ("data_2", "data_2"), ("data_3", "data_3"), ("data_4", "data_4"),) my_choice = forms.MultipleChoiceField(choices=CHOICES, widget=forms.CheckboxSelectMultiple()) class Meta: model = MyModel fields = ["remark"] view class MyView(UpdateView): model = MyModel form_class = MyModelForm template_name = "mytemplate.html" def form_valid(self, form): selected_choices = self.request.POST.getlist("my_choice") for item in selected_choices: form.instance.item = False form.instance.remarks = form.cleaned_data["remark"] form.instance.save() return super(MyView, self).form_valid(form) what i want is, i want to take the selected choices and change its value to False by checking the checkbox and remaining must be unaffected.Please help.... -
Django-Bootstrap formset not displaying group select as dropdown
I have a formset to display a selected subset of User information, and allow permitted people to edit it. Part of that is the users Group membership. The formset is created with modelformset_factory from django's built in User form. The problem I have is that the group field is not rendering as a dropdown. It shows all of the groups as a block, with the selected group highlighted. The template renders the form with <form action="{% url 'users:profiles' %}" method="post"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} <div class="row form-row"> {% bootstrap_form form show_help=FALSE %} {% buttons %} <button name="submit" class="btn btn-primary btn-sm">Submit</button> {% endbuttons %} </div> {% endfor %} </form> </div> I have tried rendering each field seperately with {% bootstrap_field %}, and the group as a <select>. That rendered correctly, but then trying to change on users detail caused every form to error. Is there a way to have a dropdown in a formset? -
Fetching proper data in flutter app from djano-rest
Here I'm creating a moblie app with flutter. Also I've created the back-end with django rest framework. And now I want to use the informations on my back-end in the flutter. For Registration, I can post my user info from flutter to django rest, It works proberly. But when some of inputs are incorrect I don't know how to reflect the problem form back-end into the flutter app. For example here, the email address is incorrect: enter image description here And this is my code for fetching and getting data: void _postmessage( {@required var username, @required var email, @required var password1, @required var password2}) async { var url = 'url'; var data = { "username": username, "email": email, "password1": password1, "password2": password2 }; HttpClient httpClient = new HttpClient(); IOClient ioClient = new IOClient(httpClient); ioClient.post(url, body: data); _fetchdata(); } _fetchdata() async { List list = List(); final response = await http.get('url'); if (response.statusCode == 200) { list = json.decode(response.body) as List; print(list); } else { // list = json.decode(response.body) as List; print(json.decode(response.body)); } } As the result I get this in the output: enter image description here It's printing this on the output: flutter: {detail: Method "GET" not allowed.} Thank you … -
Renaming user model
I'm following the guide provided in this answer, but I've run into an issue. I'm renaming myauth.MyUser to myauth.User. I created my first set of migrations from other apps, converting every ForeignKey to an IntegerField. The migrations were created fine. I then changed the name or my User model and created a migration, this was also fine. I created my third set of migrations changing the fields back to ForeignKeys to the new model. These migrations also created fine. I then manually added dependencies to the migration files, so that the FK -> Int migrations required the previous version of the user app, and the Int -> FK migrations required the latest, renaming migration. All seems fine, however when I try to run manage.py migrate, I get the following error (a lot of times - for each FK): The field otherapp.Model.user was declared with a lazy reference to 'myauth.user', but app 'myauth' doesn't provide model 'user'. What is going on? Is there a way out of this situation? -
Django. Integrate modelformset_factory in template
Im trying to integrate modelformset_factory in my template like this: <div class="create_steps_item" data-step="3"> <form method="POST" id="path_form"> {% csrf_token %} <div class="form_title">3. Выбрать папки</div> <div class="form_folders"> <div class="form_folder"> <div class="ftp_form_item"> <div class="ftp_form_item_add"></div> <div class="ftp_f_long ftp_f_long_i"> <div class="input-effect"> {{ ftppath.path }} <label>Путь на сервере</label> <span class="focus-border"></span> </div> </div> <div class="ftp_form_s ftp_form_s_i"> <div class="checkbox_box"> {{ ftppath.recursive }} <label for="check"> <span> <!-- This span is needed to create the "checkbox" element --> </span> Рекурсивно </label> </div> </div> </div> <div class="ftp_form_item ftp_form_item_type"> <div class="select_wrapper"> {{ ftppath.period }} <div class="select_wrapper_val"></div> <span class="select_wrapper_label">Период</span> <div class="select_list"> <div class="select_list_item">Раз в сутки</div> <div class="select_list_item">Раз в неделю</div> <div class="select_list_item">Раз в 2 недели</div> </div> </div> </div> </div> </div> <div class="form_button form_button_ftp"> <button class="btn" type="submit" name='done'> <span>Готово!</span> </button> <div class="form_button_message form_button_message_red"> <span class="form_message_bad"></span> <div class="form_message_text"> <b>Ошибка : </b> Такой папки не существует! </div> </div> </div> </form> But if i use {{ ftppath.period }} for example, it doesnt have any effect, i have just empty space. If i put in template {{ ftppath.as_p }}, form is rendering, but structure is not correct for me. How can i put my form field in places where i need? My form: class FtpPathForm(forms.ModelForm): path = forms.CharField(widget=forms.TextInput(attrs={'type':'text','class':'effect-16'}), required=False) recursive = forms.BooleanField(widget=forms.CheckboxInput(attrs={'id':'check'}), required=False) period = forms.CharField(widget=forms.TextInput(attrs={'type':'text','style':'display:none'}), required=False) class Meta: … -
How to inherit from a template that is in another app on Django?
I have set up a base.html file in /common/templates/ that the apps in my project should inherit from. I have set up my buil paths like so: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) COMMON_TEMP_DIR = os.path.join(BASE_DIR, 'common') my templates like this: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [COMMON_TEMP_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], 'debug': DEBUG, }, }, ] and have listed the apps using base.html in settings.py. However, the contents of the inheriting HTML files are not showing up when base.html is loaded. What am I doing wrong here? -
django.core.exceptions.ImproperlyConfigured: WSGI application 'btre.wsgi.application' could not be loaded; Error importing module
I am trying to learn django framework and getting this error when trying to run the server. Can anybody please point me to the right direction. Things were working fine, before I ran the python manage.py collectstatic and then created the templates. Seems like I am getting an error importing module error but I am not sure what to look into. Django settings for btre project. Generated by 'django-admin startproject' using Django 2.1.3. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ 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.1/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'pages.apps.PagesConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewnoMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'btre.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'btre.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': … -
Djanog middleware process view after done with return render template continue to regular page
I created a custom django middleware, class CustomMiddleware(object): def process_view(self, request, view_func, *view_args, **view_kwargs): ... ... return render(request, 'accounts/xyz_form.html', {}) Now in xyz_form.html there is a form which on submit action goes to url which call the view and view save the form data. Now after the form data is saved how can that form disappear after the view complete its execution and continue with its normal execution. So what url should I pass in urls.py to call that view and on calling view the middleware gets exit. -
Is using jquery parseHTML to remove script tags enough to prevent XSS attacks?
We are using a WYSWIG Editor(Froala Editor) and storing raw HTML that is created by the user. Thus, escaping the string is not an option. I am intending to store the HTML string in a variable or a data-attribute enclosed within quotes. Then, read that HTML string and remove script tags using jquery's parseHTML as well as keep only certain attributes before loading the HTML into the editor. Is this approach enough to prevent all XSS attacks? -
Enumerate number in django template
It's a question by curiosity : So i have 4 types of choice for field of a model. class Thing(models.Model): Cat_One = (("b", "Big"), ("s", "Small"),("a","very small"),("x","xtra small")) dateCreation = models.DateTimeField(null=True, blank=True) url = models.CharField(null=True, blank=True, max_length=800) name = models.CharField(blank=True, null=True, max_length=200) catOne = models.CharField(max_length=1, choices=Cat_One, blank=True, null=True) so i can pass the choice to the django template : {% for choice in cat_One %} ... And iterate. But i would like to know , how to iterate from 1 to 4 without passing something to the django template ? Is there a way to do : {% for number in [1,2,3,4] %} or something with a forloop counter ? regards -
Storing and running user defined functions from a database in Django
This is a rather weird use-case, however, a project we are developing needs a way for it to store user-defined functions and run them within views. The function code will be stored in a TextField in a model. The functions themselves would be ideally very simple, mostly involving arithmetic operations, if-else blocks, and loops. The functions can also be in any language, as long as Python is able to run them somehow. The obvious problem is the possible security issues, since it is always best to assume the code will come from untrusted sources. Anyway, we have thought about these possible solutions: Storing Python functions as strings, and running them using eval(). Storing Javascript functions as strings, and running them using Js2Py. Creating a simple programming language, a subset of Python, which removes all the methods and operators which could possible cause security issues. The function would therefore be written in this new language. What is my best option? Obviously, the first two options are very insecure, while the third one is hard to implement. Is there a better way to do this? -
Showing the list of pull_requests on the homepage
% extends "base.html" %} {% load static %} {% block body %} <div class="container"> {% if pullrequests %} {% for field in pullrequests %} <table> <tr> <th>{{ field.pr_project }}</th> <th>{{ field.pr_id }} </th> <th>{{ field.nd_comments }} </th> <th>{{ field.nb_added_lines_code }}</th> <th>{{ field.nb_deleted_lines_code }}</th> <th>{{ field.nb_commits }}</th> <th>{{ field.nb_changed_fies }}</th> <th>{{ field.Closed_status }}</th> <th>{{ field.reputation }}</th> <th>{{ field.Label }}</th> </tr> </table> {% endfor %} {% else %} <strong> There is no pull request in the database. </strong> {% endif %} </div> {% endblock %} def get_queryset(self, request): pull_requestsList=Pull_Requests.objects.all() pullRequest_dict={'pull_requests': pull_requestsList} #print(pull_requests) #args={'form': Pull_Requests,'pull':pull_requests } return render(request, 'templates/home.html', pullRequest_dict) I have a model Pull_Requests in my database that's containing data and I want to display this data into an HTML table on my homepage. So I created the view and home template as they are below but I'm getting nothing when I run the app. As I am new in this area, I'm not able to detect what could be the issue. Thanks in advence for your help. -
How do I get Django to display what, I want in database
Thanks for helping I'm sorry I'm poor in programming Ok I trying to take data out my database (SQLlites3) and display all at once this my code for views def index(request): tank = tank_system.objects.all() args = {'tank':tank} return render(request,'FrounterWeb/includes.html',args) and here are my HTML that place {% block content %} <div class ="table-responsive-sm"> <!-- tables tiles --> <table class ="table table-bordered table-responsive-sm"> <tr> <th>Time</th> <th>EC</th> <th>pH</th> <th>Tank level</th> <th>room temptures</th> <th>Water temptrure</th> </tr> {% for tank_system in tank %} <tr> <td>time</td> <td>{{tank.EC}}</td> <td>{{tank.PH}}</td> <td>{{tank.WaterLevel}} lites</td> <td>{{tank.TempRoom}} C</td> <td>{{tank.TempWater}} C</td> </tr> {%endfor%} </table> </div> {% endblock %} the end result objects.all() result but if i would to modified to with objects.get(id=x) here modified views; def index(request): tank = tank_system.objects.get(id=1) args = {'tank':tank} return render(request,'FrounterWeb/includes.html',args) and adjustment made in HTML; {% block content %} <div class ="table-responsive-sm"> <!-- tables tiles --> <table class ="table table-bordered table-responsive-sm"> <tr> <th>Time</th> <th>EC</th> <th>pH</th> <th>Tank level</th> <th>room temptures</th> <th>Water temptrure</th> </tr> <tr> <td>time</td> <td>{{tank.EC}}</td> <td>{{tank.PH}}</td> <td>{{tank.WaterLevel}} lites</td> <td>{{tank.TempRoom}} C</td> <td>{{tank.TempWater}} C</td> </tr> </table> </div> {% endblock %} and end result for this is objects.get(id=) result I grantnee that the database pass jqury data/object into my html, but now i'm stump on how fix this? please help … -
Django REST - How count view hits / counts for specific DRF view action?
I'm trying to find a proper solution to count object views. In particular, I have a model called Content which contains a media/video file and meta-data (title, keywords, etc.). I would like to track when the user has access to it, I was thinking to use django-hitcount to track retrieve action on my ContentViewSet: https://django-hitcount.readthedocs.io/en/latest/installation.html?highlight=view How I can use it with DRF? My DRF viewset: class ContentViewSet(ModelViewSet): """ Viewset for retrieving, listing, creating, updating, and destroying `Content` instances. """ permission_classes = (permissions.IsAuthenticated,) queryset = Content.objects.all() serializer_class = ContentSerializer # Doc: http://djangorestframework.readthedocs.io/en/latest/api-guide/filtering/ filter_backends = [SearchFilter, DjangoFilterBackend, OrderingFilter] pagination_class = DefaultPageNumberPagination ordering = ['-id'] ordering_fields = [ 'id', 'title', ] def get_serializer_context(self, *args, **kwargs): return {"request": self.request} def perform_create(self, serializer): serializer.save(owner=self.request.user) -
How to manipulate data between views and template in Django?
I'm working on a project called emotion detection from voice . I've to upload an audio file and extract its features, and classify it on basis of emotion , the project has been completed in Python. I'm having trouble integrating it with Django , after uploading the file in Django , I don't know how to pass it to the views for feature extraction and classification . How can I pass data between my template and views , and vice versa? -
How to use the parallel flag in django test calls when using psycopg2 for postgresql calls inside of the tests
When we use ./manage.py test ... all is well. Once we add --parallel 8 (as we have quad core machines with HT), we get "connection already closed" errors from psycopg2. This answer seems to suggest that the issue lies in the fact that django creates a connection and then starts branching off from the main thread --> all threads really share the connection. Now if one of them closes the connection, all their connections are closed and the DB starts refusing transactions on that conn. How do we go ahead and allow testing our codebase without having to mock all DB calls now? Personally, I'd like to mock the DB but (according to project mgmt) it will be an enormous overhead to fix several hundred tests for this. So: Is there A) a nice drop in DB mock that might keep all records in memory for tests or B) a way to allow several threads to work with psycopg2? -
DJANGO MULTIPLE IMAGES UPLOAD FOR A POST
Please help me. I am new to Django, cannot undertsand the following. I have subclass of CreateView for creating a post. I'm creating a rental site project where people can post their apart and attach files (images) to it. One should have possibility to attach as many images as he wants to ONE form. I have found in Internet a decision that I need to use 2 models - 1 model for post + 1 separate model for images. Is it so? Post form is created and handled in my views.py by sublass of CreateView. Now how to connect new separate model for images with my CreateView ? And save all images to the current Post Form? Thanks in advance models.py class Post(models.Model): post_author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) post_title = models.CharField(_('Title'),max_length=200, null=True, blank=False) post_type = models.CharField(_('Type'),max_length=18, choices=post_type_list, default='appart') post_content = models.TextField(_('Your post description'),blank=True) post_created_date = models.DateTimeField(default=timezone.now, help_text=_('Post creation date and time.'),) post_published_date = models.DateTimeField(null=True, blank=True, help_text=_('Post publication date and time.'),) def get_absolute_url(self): return reverse("posts:post_details", kwargs={'pk':self.pk,'post_type':self.post_type}) class Post_Gallery(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) current_hour = datetime.datetime.now() images = models.ImageField(_('Upload some pictures'),upload_to='uploads/%Y/%m/%d/{}'.format(current_hour.hour), max_length=100, null=True, blank=True) def __unicode__(self): return self.images.url forms.py class NewPostForm(forms.ModelForm): class Meta: model = Post fields = [ 'post_title','post_type','post_content', ] class GalleryForm(forms.ModelForm): … -
Can anyone told me how to prevent to store blank input field of multiple input in Django Models
In my form there are multiple input field means there are two fieldset in which same input fields are available and i want to store both that input into models in different ids. It is working but when i filled only one input field and click on submit button then the second one is also stored blank but i want to prevent it. It's means that i only want to store filled input field into model and blank one will not not stored. My Form.html <form class="well form-horizontal" method="post" action="{% url 'fixed_doclist' %}"> {% csrf_token %} <fieldset> <div class="form-group"> <label class="col-md-4 control-label">Document Name</label> <div class="col-md-6 inputGroupContainer"> <div class="input-group"><span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span><input id="fullName" name="dname" placeholder="Full Name" class="form-control" value="" type="text"></div> </div> </div> <div class="form-group"> <label class="col-md-4 control-label">Exp Date</label> <div class="col-md-6 inputGroupContainer"> <div class="input-group"><span class="input-group-addon"><i class="glyphicon glyphicon-home"></i></span><input id="postcode" name="exp" placeholder="Postal Code/ZIP" class="form-control" value="" type="text"></div> </div> </div> <div class="form-group"> <label class="col-md-4 control-label">Renewal Date</label> <div class="col-md-6 inputGroupContainer"> <div class="input-group"><span class="input-group-addon"><i class="glyphicon glyphicon-home"></i></span><input id="postcode" name="renewdt" placeholder="Postal Code/ZIP" class="form-control" value="" type="text"></div> </div> </div> <div class="form-group"> <label class="col-md-4 control-label">Purpose</label> <div class="col-md-6 inputGroupContainer"> <div class="input-group"><span class="input-group-addon"><i class="glyphicon glyphicon-home"></i></span><input id="state" name="purpose" placeholder="State/Province/Region" class="form-control" value="" type="text"></div> </div> </div> <div class="form-group"> <label class="col-md-4 control-label">Remarks</label> <div class="col-md-6 inputGroupContainer"> <div class="input-group"><span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span><input … -
Is it possible to get 0 count for group by queries when there are no rows for that particular group by
For eg: We have two tables Note -------------------- id | text | label_id 1 | abcs | 1 2 | accs | 2 3 | abts | 1 Label --------- id | name 1 | pro 2 | foo 3 | bar Now the data I want is Label Name | Note Count ------------------------ pro | 2 foo | 1 bar | 0 Now if I do this: Note.objects.all().values('label__name').annotate(count=Count('id', distinct=True)) I wont get the 3rd row, which is (bar, 0). Is there any way to get this information? Condition being it has to be done in a single query and the query should be on Notes model and not start from the Label model -
How to auto initialize fields in a Django model?
I have the following model in Django and basically I need to to auto initialize 3 out of 5 fields once the user has inserted some data, i.e., Models.py class Assignment(models.Model): assignment = models.CharField(max_length=60) comments = models.CharField(max_length=60) starting_date = models.DateField() points = models.IntegerField() STATUS = (('A', 'Active'), ('C', 'Cancelled'), ('D', 'Done')) status = models.CharField(max_length=1, choices=STATUS) Forms.py from django import forms from .models import Task class TaskForm(forms.ModelForm): class Meta: model = Task starting_date = datetime.now() fields = ['task_description', 'task_comments', 'starting_date', 'priority', 'points'] Input form <!-- Input form to request to values--> <div class="panel-heading">Add a new assignment </div> <form id ="insert_new_assign" class="form-horizontal" method="POST"> {% csrf_token %} <div class="panel-body"> <div class="input-group"> <input class="form-control" name="insert_new_assign_field" type="text" placeholder="Insert your new assignment here" /> <input class="form-control" name="insert_new_comment_field" type="text" placeholder="Any comment you want to add?" /> <button class="btn btn-primary" type="submit">Add</button> </div> </form> </div> See the JS fiddle for quick reference Basically when the user enters a new assignment and comment, I want Django to save these two fields and auto initialize the other fields with the current time, 0 points and A status. Whenever I try to to save a new record, I get the error The view engine.views.home didn't return an HttpResponse object which is normal … -
in Djanog rest FRamework sendign json reqeust but i want to extra key value json response
i have this json formate { "hashofblock": "abcd21", "blockid": 1, "nooftxn": 2, "hashprev": "defg234", "txn": [ [ "3", "F", "H", "Xdffscdgf" ], [ "5", "a", "f", "xdfvfdgf" ], [ "4", "a", "f", "xdfvfdgf" ] ] } but after sendig the request of that json. i want that jon become one other pair of key and value and extra header i.e is hash of the request json value lik this { header:'uueouworw9780udfihhgnnweirwurw' body:{ { "hashofblock": "abcd21", "blockid": 1, "nooftxn": 2, "hashprev": "defg234", "txn": [ [ "3", "F", "H", "Xdffscdgf" ], [ "5", "a", "f", "xdfvfdgf" ], [ "4", "a", "f", "xdfvfdgf" ] ] } } jsondata=Json_data=json.load(request.body.decode("utf-8")) header = hashlib.sha256(jsondata.encode('utf-8')).hexdigest() response_data={'Header' : header,'Body' : jsondata}