Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Testing in python a part of a class method
here's my problem. I'm new to python testing (testing in general) and i'm working with Python 3.x and Django 2.0. I have a class which has the goal of starting a synchronization between two DBs. It has a method for the synch, and this method is composed in different parts: Send an HTTP Request to the other server (it tries to send the request for a certain amount of attempts, then it stops); Check the result (response received or number attempts exceeded); Check the Response (Status code, format, response content (It's a JSON), ...) After that, it starts again doing this, while there's nothing to synchronize. Now, i need to test this different parts separately, but i don't know how because, as i said, this ops are all in the same method. I thought a solution would be separate this operation in different "sub" methods (only for testing purpose) or execute those parts of code in different tests. Is there a better solution? -
Combine two querysets
I have 2 querysets from 2 different models like this: qs1=[username, lastname, firstname] qs2=[username, email] I need to combine them to one and sorted by username. So it becomes like this: qs=[username, lastname, firstname, email] qs1 and qs2 are querysets with multiple entries. I have code in view.py like this: usernames = C.objects.values('username') for username in usernames: try: qs1=A.objects.filter(username=username).values('username','lastname',' 'firstname') qs2=B.objects.filter(username=username).values('username','email') How do I combine qs1 and qs2 to qs? -
Call Django on HTML button click
I'm trying to make a basic sort function for a Django project, but I don't know how to call the sort function when I click the 'sort' button Django view: def sort_btn(request): if request.GET.get('sort-btn'): cits = Citizen.objects.all().order_by('name') return render_to_response(request, 'civil_reg/index.html', {'cits': cits}) HTML button: <button name="sort-btn" id="sort-btn">sort</button> -
Returning Hex UUID as default value for Django model charfield
I tried to create a model with identifier generated from uuid4. But what I want instead of regular uuid, I want identifier has hex uuid format (without "-"). Here is what I tried: class Model(models.Model): identifier = models.CharField(max_length=32, primary_key=True, default=uuid.uuid4().hex, editable=False) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) def __str__(self): return self.identifier class Meta: abstract = True instead of returning unique id every time inherited class instantiated, it returns the same id because of uuid4(). I tried to change the default value from uuid.uuid4().hex to uuid.uuid4.hex but it seems the hex is not callable from uuid4 directly. So what is the possible way to produce default value for my identifier from uuid with hex format? -
I need an example for update_or_create using JsonField
I need an example using update_or_create for JsonField (I didn't found an example in docs) I found only for "normal" fields: Prod.objects.update_or_create(type=type_key, parent_id=parent_id, prod_id=prod_id, defaults={'ol': new_path}) So if a key exist, update the key if not create it. -
django apps : operational error
i make cart app for ecommerce site to handle users sessions this is the cart model it give me an error in the admin page when clicking on carts section from django.db import models from django.conf import settings from django.urls import reverse from products.models import product user=settings.AUTH_USER_MODEL class cart(models.Model): user = models.ForeignKey(user, null=True, blank=True) products = models.ManyToManyField(product, blank=True) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) def __unicode__(self): return str(self.id) -
How to upload a folder to django database through form
I want to upload a folder containing few files, and save those files to the database. I was successful in uploading a file, but facing problem while trying to upload a folder. The files does not get stored in the database. Can someone please tell me where am I going wrong. models.py class Document(models.Model): report_id = models.CharField(max_length=50, blank=False) description = models.CharField(max_length=255, blank=False) document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True) is_diagnoised = models.BooleanField(default=False) uploaded_by_doc = models.CharField(max_length=20, default="") downloaded_by_rad = models.CharField(max_length=20, default="") forms.py class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ('report_id', 'description', ) views.py def index(request): if request.user.is_authenticated: uid = request.user.id usern = request.user.username if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): for afile in request.FILES.getlist('document'): new_file = Document(document = afile) post = form.save(commit=False) post.uploaded_by_doc = usern post.document = form.cleaned_data.get('new_file') post.save() return HttpResponseRedirect('index') else: form = DocumentForm() return render(request, 'upload.html', context) upload.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="file" name="document" multiple = "true" webkitdirectory="true" directory = "true"/> <button type="submit">Upload</button> -
Django ArrayField from unicode
I have an array field in PostgreSQL (Table name is group): users TEXT [] I used a 3rd party tool to migrate my data in a read-only DB, and that has converted my array to unicode. Now, I want to use this array data in Django and was using Django's ArrayField for this. Is there any way, I can convert that unicode data to Array in the model class? My model is something like: class Groups(models.Model): id = models.TextField(primary_key=True) users = ArrayField(blank=True, null=True, base_field=models.TextField()) When I print the object's user field, I get this output: u'{pradeep.kumar}' -
Multiple Integer Arguments in Django Rest Framework Router URL
I'm setting up a url using Django Rest Framework viewsets and routers, and I'm trying to get the url to accept two values: first, to filter objects by a user id, and then by the object's id. (In my case, the objects are from a model called Request.) For example, mysite.com/api/requestsbyuser/1/ would return all Request objects for user 1, and mysite.com/api/requestsbyuser/1/23/ would return Request object with pk=23 for user 1. Right now I have: # urls.py from django.conf.urls import url, include from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(prefix=r'requestsbyuser/(?P<user_id>.+)', viewset=views.RequestsByUser, base_name='request') urlpatterns = [ url(r'^', include(router.urls)), ] # views.py class RequestsByUser(viewsets.ModelViewSet): serializer_class = RequestsSerializer def get_queryset(self): u_id = self.kwargs['user_id'] return Request.objects.filter(user_id=u_id) This works well for listing all Request objects when the url is passed in only the user_id. But when I try to go to mysite.com/api/requestsbyuser/1/23/, I get the error: invalid literal for int() with base 10: '1/23'. Django debugging says that the following four url patterns are in my URLConf: ^api/ ^ ^requestsbyuser/(?P<user_id>.+)/$ [name='request-list'] ^api/ ^ ^requestsbyuser/(?P<user_id>.+)\.(?P<format>[a-z0-9]+)/?$ [name='request-list'] ^api/ ^ ^requestsbyuser/(?P<user_id>.+)/(?P<pk>[^/.]+)/$ [name='request-detail'] ^api/ ^ ^requestsbyuser/(?P<user_id>.+)/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='request-detail'] Am I missing something? I thought the DRF router would handle url paths with individual object primary key values, … -
data did'nt validate error django
Can anyone please help me..... I keep on getting "data didn't validate" error when saving data from a ModelForm. Everything worked fine for me until I added some CSS and JS for the frontend, used form widgets and manually displayed the form field on the template. Here are the codes: forms.py from django import forms from .models import List_of_Res class fordtp(forms.Form): month_choices=( ('JAN','January'), ('FEB','February'), ('MAR','March'), ('APR','April'), ('MAY','May'), ('JUN','June'), ('JUL','July'), ('AUG','August'), ('SEP','September'), ('NOV','November'), ('DEC','December'), ) day_choices=[] for ddd in range(1,32): day_toS=(str(ddd),str(ddd)) day_choices.append(day_toS) year_choices=[] for yyy in range(1990,2100): year_toS=(str(yyy),str(yyy)) year_choices.append(year_toS) month = forms.ChoiceField(choices = month_choices,widget=forms.Select(attrs={'class':'form-control form-control-sm'})) year = forms.ChoiceField(choices = year_choices,widget=forms.Select(attrs={'class':'form-control form-control-sm'})) day = forms.ChoiceField(choices = day_choices,widget=forms.Select(attrs={'class':'form-control form-control-sm'})) class ResearchForm(forms.ModelForm): class Meta: model = List_of_Res fields={ 'prog_title', 'proj_title', 'stud_title', 'prog_lead', 'stud_lead', 'co_res', 'res_site', 'campus', 'category_res', 'classif_res', 'amt_granted', 'date_started', 'res_status', 'date_completed', 'res_SF', 'res_pubstat', 'res_JN', 'res_JV', 'date_pub', 'res_iprstat', 'apptype', 'date_appl', 'date_pprv', 'app_pending', 'res_abs' } widgets = { 'prog_title': forms.TextInput(attrs={'class':'form-control'}), 'proj_title': forms.TextInput(attrs={'class':'form-control'}), 'stud_title': forms.TextInput(attrs={'class':'form-control'}), 'prog_lead': forms.TextInput(attrs={'class':'form-control'}), 'stud_lead': forms.TextInput(attrs={'class':'form-control'}), 'co_res': forms.Textarea(attrs={'class':'form-control','placeholder':'Enter 1 name per line'}), 'res_site': forms.Textarea(attrs={'class':'form-control','placeholder':'Enter 1 site per line'}), 'campus': forms.Select(attrs={'class':'form-control'}), 'category_res': forms.RadioSelect(attrs={'class':'form-check-input'}), 'classif_res': forms.Select(attrs={'class':'form-control'}), 'amt_granted': forms.TextInput(attrs={'class':'form-control'}), 'date_started': forms.DateInput(attrs={'placeholder':'YYYY-MM-DD','class':'form-control'}), 'res_status': forms.RadioSelect(attrs={'class':'form-check-input'}), 'date_completed': forms.DateInput(attrs={'placeholder':'YYYY-MM-DD','class':'form-control'}), 'res_SF': forms.CheckboxSelectMultiple(attrs={'class':'form-check-input'}), 'res_pubstat': forms.RadioSelect(attrs={'class':'form-check-input'}), 'res_JN': forms.TextInput(attrs={'class':'form-control'}), 'res_JV': forms.TextInput(attrs={'class':'form-control'}), 'date_pub': forms.DateInput(attrs={'placeholder':'YYYY-MM-DD','class':'form-control'}), 'res_iprstat':forms.RadioSelect(attrs={'class':'form-check-input'}), 'apptype':forms.RadioSelect(attrs={'class':'form-check-input'}), 'date_appl':forms.DateInput(attrs={'placeholder':'YYYY-MM-DD','class':'form-control'}), 'date_pprv':forms.DateInput(attrs={'placeholder':'YYYY-MM-DD','class':'form-control'}), 'app_pending': forms.RadioSelect(attrs={'class':'form-check-input'}), 'res_abs': forms.Textarea(attrs={'class':'form-control'}) } (views.py): from … -
Combining multiple Regex
im looking to combine multiple regexes using a AND condition. For example, the following words should not be matched (starting of string): database audit index analysis extract good bad The strings that start with these strings will not be matched. Similarly, words such as others, error will be matched. I have done a regex that is able to filter for each word but has not been successful at filtering out the list of words to be not matched. #This will only match those that do not start with database r'(^((?!database).+)' While trying to combine, it has failed to check both conditions. r'(^((?!database).+)(^((?!audit).+)))' Note: This regex is to be used in the django framework, urls.py file -
Unable to connect to gunicorn via Ingress
I'm trying to deploy a Django application on Kubernetes. I'm using Gunicorn to serve the Django application. Gunicorn accepts connections when running at 0.0.0.0:8000, but not 127.0.0.1:8000. Can anyone help explain why? Kubernetes service.yaml ... spec: type: NodePort ports: - protocol: TCP port: 80 targetPort: 8000 ... Kubernetes deployment.yaml ... spec: containers: - name: app image: <img> livenessProbe: httpGet: path: /healthz port: 8000 initialDelaySeconds: 10 ports: - protocol: TCP containerPort: 8000 env: ... Dockerfile ... CMD python manage.py makemigrations && \ python manage.py migrate && \ gunicorn -w 3 app.wsgi:application Django app/settings.py ... DEBUG = True ALLOWED_HOSTS = [os.environ.get('ALLOWED_HOSTS')] ... Container startup logs No changes detected Operations to perform: Apply all migrations: <migrations 1..n> Running migrations: No migrations to apply. [2018-01-25 06:35:30 +0000] [9] [INFO] Starting gunicorn 19.7.1 [2018-01-25 06:35:30 +0000] [9] [INFO] Listening at: http://127.0.0.1:8000 (9) [2018-01-25 06:35:30 +0000] [9] [INFO] Using worker: sync [2018-01-25 06:35:30 +0000] [12] [INFO] Booting worker with pid: 12 [2018-01-25 06:35:30 +0000] [13] [INFO] Booting worker with pid: 13 [2018-01-25 06:35:30 +0000] [14] [INFO] Booting worker with pid: 14 Error message when going through an Ingress mapped to a domain name (eg. curl example.com) <html><head> <meta http-equiv="content-type" content="text/html;charset=utf-8"> <title>502 Server Error</title> </head> <body text=#000000 … -
Django Pagination "Page not found"
I'm currently having issues with my Django pagination. I have a query set of 9 objects and am paginating one object to a page. So I should have 9 pages total. Paginator is showing that I have 9 pages, but when I click the "next" page button my (Always on the last/last two pages) my url turns to: http://127.0.0.1:8000/forum/1?page=7 Then I get a 404 page not found error along with "Invalid page (7): That page contains no results" Here is my class code: class DirectoryClass(generic.ListView): template_name = "forum_directory.html" model = Directory paginate_by = 1 def get_context_data(self, **kwargs): context = super(DirectoryClass, self).get_context_data(**kwargs) directory = Directory.objects.filter(pk=self.kwargs['directory_id']) context['page'] = 'forum' context['name'] = directory.first().name context['user'] = self.request.user topic_set = directory.first().topic_set.all().order_by('-last_post') print(topic_set.all()) paginator = Paginator(topic_set, self.paginate_by) page = self.request.GET.get('page') try: topic_set = paginator.page(page) except PageNotAnInteger: topic_set = paginator.page(1) except EmptyPage: topic_set = paginator.page(paginator.num_pages) context['topics'] = topic_set context['page'] = page return context What am I doing wrong here? I'm completely lost. Thank you! -
Django model property with parameter
I've the following models in Django. class User(models.Model): name = models.CharField(max_length=50) ... ... @property def get_info(self, key=None): value = self.name if key else 'Hello World' return value But when I try to execute the code in Django shell, I'm getting the following error. n [4]: user = User.objects.get(id=1) n [5]: user.get_info(key='test_key') --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-5-f7b917070aee> in <module>() ----> 1 user.get_info(key='test_key') TypeError: _get_info() takes exactly 2 arguments (1 given) -
nginx+uwsgi+django emperor mode not working
I am doing multi-application nginx+uwsgi setup in django. I am following this documentation to set up emperor mode for my project. It works fine when I run "uwsgi --ini myproject_uwsgi.ini" but I am not able to deploy emperor mode following this documentation. I have researched many docs but not able to find relevant information related to emperor mode setup. My nginx.conf file:(angularJS frontend) server { listen 80; server_name 192.168.xx.xx; root /home/user/Myspace/workspace/Myproject_frontend/dist; } My "etc/uwsgi/vassals/uwsgi.ini" file looks like: [uwsgi] #Django-related settings #Django's wsgi file wsgi-file = /home/user/Myspace/workspace/myproject/myproject/wsgi.py http = 192.168.xx.xx:8080 virtualenv = /home/user/Myspace/VENV_MYPROD Also, i have created a uwsgi.service file in "/etc/systemd/system/uwsgi.service" to start emperor mode service and it looks like: [Unit] Description=uWSGI Emperor service After=syslog.target [Service] ExecStart=/usr/local/bin/uwsgi --emperor /etc/uwsgi/vassals/ RuntimeDirectory= uwsgi Restart=always KillSignal=SIGQUIT Type=notify StandardError=syslog NotifyAccess=all [Install] WantedBy=multi-user.target Please provide help on setting up uwsgi emperor mode. -
django-import-export specify id in order from ‘1’
Hi,When I import data from excel, I find the default id is random: ID NAME 5 A 9 B I want to like below when I import data "NAME: A, NAME: B" from excel : ID NAME 1 A 2 B How should I do? -
Run a cron job to check the due date of a task
I'm working in an integration between Django and Chatfuel. Right now the bot is almost complete, I have difficulties with the last task, I have certain tasks to do and each them have a due time, so three days before it expires I have to send a message to my client remindering him/her that he/she have to complete this task. I'm available to obtain the messenger_user_id after the first interaction with my bot, now, I know i have to run a cron job at a frequent interval to check the due date and if it's close, send a message through Broadcasting API. But I don't know how to achieve that goal. models.py class Tasks(models.Model): task = models.CharField(max_length=100) objective = models.TextField() created_date = models.DateTimeField( default=timezone.now) due_date = models.DateTimeField( default=timezone.now) def __str__(self): return self.task views.py #in here I obtain user's fb id def save_fb_id(request, username, fb_id): profile = Profile.objects.get(user__username=username) if profile.fb_id != fb_id: profile.fb_id = fb_id profile.save() return HttpResponse() -
errors while running python scripts triggered by django app
I am building a fully open source testrunner for my needs but I am running into some problems. the test runner parses a yaml file for a set of scripts in various paths and executed the scripts and uses a lib that i will be creating to return the outcome. right now i have a simple ping script that im working to get running and testing as i progress but i am getting a lot of errors. the errors are below and all the source code is also shown below the errors. The github repo for this is here. feel free to pull it in and test the issues i am seeing. https://github.com/castaway2000/testrunner The issue: I am trying to use the testrunner i built to parse a yaml file for paths to scripts i am writing for projects im using. For example if want to use a group of certain tests on a target, i can make a yaml file for each set of the types of tests. There is a certain problem I am seeing with this however, the relative path and exact path of the files are not able to use the django libraries, cause its unable to … -
Django rest framework & external api
i wanna get my data from an external API (https://example.com/consumers). Can I build my urls.py like this? url(r'^(?P<test.com/consumers)>[0-9]+)$/', views.get, name="get"), Or do you have any other(s) good idea(s) ? Thanks. -
Integrity Error: using primary_key=True
This is my Models: from django.db import models from django.contrib.auth.models import User class Bookmark(models.Model): id = models.PositiveIntegerField(primary_key=True) name = models.CharField(max_length=50) url = models.URLField() isPublic = models.BooleanField(default=True) dateTimePosted = models.DateTimeField(auto_now=True,verbose_name="posted at") user = models.ForeignKey(User, on_delete=models.CASCADE) This is my 0001_initials.py: from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Bookmark', fields=[ ('id', models.PositiveIntegerField(primary_key=True, serialize=False)), ('name', models.CharField(max_length=50)), ('url', models.URLField()), ('isPublic', models.BooleanField(default=True)), ('dateTimePosted', models.DateTimeField(auto_now=True, verbose_name='posted at')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ] When I am inserting values using: python manage.py shell: >>from django.contrib.auth.models import User >>user = User.objects.create_user('test', 'test@abc.com', 'test@123') >>from bookmark.models import Bookmark >>bookmark = Bookmark.objects.create(name='First Bookmark', url='example.com', user=user) this error occurs: Traceback (most recent call last): File "", line 1, in File "C:\Python34\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Python34\lib\site-packages\django\db\models\query.py", line 394, in create obj.save(force_insert=True, using=self.db) File "C:\Python34\lib\site-packages\django\db\models\base.py", line 806, in save force_update=force_update, update_fields=update_fields) File "C:\Python34\lib\site-packages\django\db\models\base.py", line 836, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "C:\Python34\lib\site-packages\django\db\models\base.py", line 922, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "C:\Python34\lib\site-packages\django\db\models\base.py", line 961, in _do_insert using=using, raw=raw) File "C:\Python34\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) … -
How to fix ImproperlyConfigured in django 1.7?
ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. [2018-01-25 02:20:16 +0000] [13560] [INFO] Worker exiting (pid: 13560) Traceback (most recent call last): File "/home/web/git/myprojc/.env/bin/gunicorn", line 11, in <module> sys.exit(run()) File "/home/web/git/myprojc/.env/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 74, in run WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run() File "/home/web/git/myprojc/.env/lib/python2.7/site-packages/gunicorn/app/base.py", line 203, in run super(Application, self).run() File "/home/web/git/myprojc/.env/lib/python2.7/site-packages/gunicorn/app/base.py", line 72, in run Arbiter(self).run() File "/home/web/git/myprojc/.env/lib/python2.7/site-packages/gunicorn/arbiter.py", line 231, in run self.halt(reason=inst.reason, exit_status=inst.exit_status) File "/home/web/git/myprojc/.env/lib/python2.7/site-packages/gunicorn/arbiter.py", line 344, in halt self.stop() File "/home/web/git/myprojc/.env/lib/python2.7/site-packages/gunicorn/arbiter.py", line 393, in stop time.sleep(0.1) File "/home/web/git/myprojc/.env/lib/python2.7/site-packages/gunicorn/arbiter.py", line 244, in handle_chld self.reap_workers() File "/home/web/git/myprojc/.env/lib/python2.7/site-packages/gunicorn/arbiter.py", line 524, in reap_workers raise HaltServer(reason, self.WORKER_BOOT_ERROR) gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> this is the stacktrace I get when I try to start the project, How to fix ImproperlyConfigured in django 1.7? -
django user_permissions.clear() not work
My user_permissions.clear() and remove() can't work at all! The two print is same. And when I create a new user, the user always contains all of models permissions. class ChangeTeacherPermission(APIView): def post(self, request): user = self.request.GET.get('user', None) user = User.objects.get(username=user) print(user.get_all_permissions()) user.user_permissions.clear() print(user.get_all_permissions()) permissions = json.loads(self.request.POST.get('obj'))['permissions'] flag = json.loads(self.request.POST.get('obj'))['flag'] class User(BaseUser): class BaseUser(AbstractBaseUser, PermissionsMixin): -
Django save and enter data after API call in views
I have 2 django project, D1 and D2. D1 has a table call T1 and D2 has a table call T2. So i have a view in D1 that do api call to the api in D2 and save the value that i get after a POST request into T1. But i also want to be able to enter data in other field of table T1. example: t2 only has book field, t1 has book and author field. When D1 do a post method to t2 in D2, it will return a book value which will be save into t1 but i also want the user to enter the author themself. How do i do it ? Here is my code models.py In D1: class T1(models.Model): book = models.CharField(max_length=10, blank=True, null=True) author = models.CharField(max_length=10, blank=True, null=True) In D2 class T2(models.Model): book = models.CharField(max_length=10, blank=True, null=True) views.py @csrf_exempt def my_django_view(request): if request.method == 'POST': r = requests.post('http://127.0.0.1:8000/api/test/', data=request.POST) else: r = requests.get('http://127.0.0.1:8000/api/test/', data=request.GET) if r.status_code == 201 and request.method == 'POST': data = r.json() testsave_attrs = { "book": data["book"], } testsave= T1.objects.create(**testsave_attrs) return HttpResponse(r.text) elif r.status_code == 200: # GET response return HttpResponse(r.json()) else: return HttpResponse('Could not save data') -
Invalid literal for int() with base 10 in template with multiple forms
I have a form that only links to one of the fields in one of my models. I'm trying to save the form, but I keep getting errors and don't know what to change. Models.py class FunctionManager(models.Manager): def editover(self, Function_id, postData): woo = Function.objects.get(id=Function_id) woo.new = postData["new"] woo.save() class Function(models.Model): tableA = models.CharField(max_length=50) new = models.TextField() def __str__(self): return str (self.tableA, self.id) objects = FunctionManager() views.py def function_page(request, Function_id): assignments = Function.objects.get(id=Function_id) context = { 'assignments': assignments, } return render (request, 'project/function.html', context) def new_save(request, Function_id): newest = WarFightingFunction.objects.editover('Function_id', request.POST['new']) return redirect ('project/function.html') urls.py url(r'^function_page/(?P<Function_id>\d+)$', views.function_page, name "function_page"), url(r'^new_save/(?P<Function_id>\d+)/$', views.new_save, name = "new_save") html <div id=new> <form action= "/SCS/new/{{assignments.id}}/" method="POST"> {% csrf_token %} <textarea name="new" id="Obox"></textarea> <input class="save" type="submit" value="Save"> </form> </div> What am I doing wrong? Thanks in advance. -
Add a field in Serializer, but the DRF is no the field
I have the Serializer to add a user_id field, see my bellow code: My PhysicalServerManualGenerateOrderSerialzier: class PhysicalServerManualGenerateOrderSerialzier(ModelSerializer): physicalserver_model = serializers.IntegerField(write_only=True) operate_system = serializers.CharField(write_only=True) extra_desc = serializers.CharField(allow_null=True, write_only=True) user_id = serializers.IntegerField(write_only=True) class Meta: model = Order fields = [ "billing_type", "buytime", "count", "physicalserver_model", "operate_system", "extra_desc", "user_id", # you see, I add the `user_id` there. ] def to_representation(self, instance): serialized_data = super(PhysicalServerGenerateOrderSerialzier, self).to_representation(instance) serialized_data['order_num'] = instance.order_num serialized_data['order_type'] = instance.order_type serialized_data['order_status'] = instance.order_status serialized_data['billing_type'] = instance.billing_type serialized_data['buytime'] = instance.buytime serialized_data['count'] = instance.count serialized_data['cost'] = instance.cost serialized_data['ctime'] = instance.ctime serialized_data['product_describe'] = instance.product_describe return serialized_data def create(self, validated_data): user_id = validated_data.get("user_id") user = User.objects.get(id=user_id) try: order = getOrder(user=user, validated_data=validated_data) except Exception as e: order = None return order My PhysicalServerManualGenerateOrderAPIView: class PhysicalServerManualGenerateOrderAPIView(CreateAPIView): """ generate order """ serializer_class = PhysicalServerManualGenerateOrderSerialzier permission_classes = [] queryset = Order.objects.all() But in the DRF, there is no user_id option: