Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django how to import file from another directory
directory structure project subproject1 app1 urls.py views.py models.py app2 urls.py views.py models.py settings.py urls.py manage.py redis.py subproject2 a.py b.py c.py i want to use settings.py and some functions return in redis.py of subproject1 inside b.py of subproject2. Is it possible? If yes how? -
Django DRF OneToOneField for muliple user types
I am trying to implement multiple user types in DRF and I'm doing that by having a User Model - which has login related fields and common fields in all the roles and also a choice field denoting type of user. Customer Model - OneToOneField with user model. Seller Model - OneToOneField with user model. I have set up authentication and permissions for User model and now I'm able to log in. I want the logged in user to be able to create his respective profile (based on user_type field of User model). class User(AbstractBaseUser, PermissionsMixin): """ A Generic User inside our system. The fields used are common to all users in letzbargain system. """ .... class Customer(models.Model): """A Class to represent a Customer in System """ user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) Now I am trying to figure out how to allow a user to create a profile respective to his user_type (customer/seller). and the more confusing part is how do I set the user to current logged in user for my CustomerSerializer or SellerSerializer This is the permission class I'm trying to use: class UpdateCustomerProfile(permissions.BasePermission): """Allow users to edit their own profile """ def has_object_permission(self, request, view, obj): """Check … -
Django-CMS NoReverseMatch
I'm trying to use Django-CMS in a existing project. I read the docs (http://docs.django-cms.org/en/latest/how_to/install.html and http://docs.django-cms.org/en/latest/how_to/apphooks.html) and I tried to solve my problem with django-cms: urls used by apphooks don't work with reverse() or {% url %} but none of these helped me. Problem: I can't reverse any url. Wheneve I try to reverse something I get this error: django.urls.exceptions.NoReverseMatch: 'poll' is not a registered namespace here is my cms_apps.py: @apphook_pool.register class PollApp(CMSApp): name = "Umfragen" app_name = "poll" urls = ["apps.poll.urls"] poll/urls.py: app_name = "poll" urlpatterns = [ # Some other paths path('', views.search, name="search"), ] heres what I tried: {% url 'poll:search' %} reverse("poll:search") reverse("de:poll:search") reverse("cms:poll:search") -
DRF does not reverse Django url pattern: NoReverseMatch
There is a complex app (not possible to just paste the code). Going to try to explain. Django There is a urls.py file from the native Django app. The urlpatterns defines and register its urls. The ^foo/ defines a group of related urls and the foonamepsace. urlpatterns = patterns('', ... url(r'^foo/', include('foo.urls', namespace='foonamespace')), ... Now there is a method generate_report which does some logic inside and then uses render_to_string to return the HTML: def generate_report(..): ... return render_to_string('foo/foo_report.html', args) Everything works inside the app, the url get reversed successfully. Django Rest Framework (DRF) Now there is a DRF implementation and one of its resources is supposed to return a report in a binary format. class PDFReportViewSet(APIView): renderer_classes = (BinaryFileRenderer, ) def get(..): ... pdf = generate_report() # <-- fails with NoReverseMatch ... return response Problem The ViewSet calls the generate_report, however one gets an error when trying to parse the HTML: NoReverseMatch: foonamespace' is not a registered namespace Question Any clues why DRF cannot reverse the namespcae/url from the the core of Django app? How to make DRF know about this particular HTML template file? -
Problems uploading files in Django
Can anyone see what im missing, im new to Django and im struggling to upload a file within a dynamically created from JSON. When the dynamically created form includes an upload it fails form.is_valid on the other hand when there is no upload the for is considered valid. i have included enctype="multipart/form-data" and request.FILES Forms.py class ProjectMandateForm(forms.Form): def __init__(self, *args, **kwargs): questions = kwargs.pop("Questions", None) super(ProjectMandateForm, self).__init__(*args, **kwargs) i = 0 while i < len(self.data['Questions']): questions = self.data['Questions'] question = questions[i].Question if question['Check'] == True: self.fields['question_%s' % i] = forms.BooleanField(label=question['Check_Question']['context']) if question['Upload'] == True: self.fields['asdf_%s' % i] = forms.FileField(label=question['Upload_Question']['context']) i = i + 1 Views.py def post(self, request): if request.method == 'POST': files = Files.objects.get(FileName="Project Mandate") self.request.session['activeFile'] = files.id mutable = request.POST._mutable request.POST._mutable = True request.POST['Questions'] = files.questions.all() request.POST._mutable = mutable form = ProjectMandateForm(request.POST, request.FILES) print(form.errors) if form.is_valid(): Template <form class="form-horizontal" method="post" enctype="multipart/form-data"> {% csrf_token %} <h1 style="width:100%; text-align:left; Font-size:25px; margin-left:10px"> Project Mandate</h1> {% for question in Questions %} <!-- account information card --> <div class="cardContainer InformationCard"> <div class="card"> <div class="card-header"> <h5 class="mb-0"> {{ question.Question.Title }} </h5> </div> <div> <div class="card-body"> {% for field in form %} {% if field.label == question.Question.Check_Question.context %} <div class="form-group " style="float:left;"> <label class="control-label" id="label_{{field.auto_id}}"> … -
Django unable to update models and not showing errors
I'm using Django 2.1 version. I have created a model AuthUserProfile and I want to update data in both User and AuthUserProfile Model. For that, I have created a ModelForm which I have overridden its __init__() method. What is the Problem I'm facing: I'm unable to update() existing data in User and AuthUserProfile Model and I do not get errors AuthUserProfile Model class AuthUserProfile(models.Model): user_profile_id = models.AutoField(primary_key=True) user = models.OneToOneField(User, on_delete=models.CASCADE) dob = models.DateField(blank=True, null=True) is_deleted = models.PositiveSmallIntegerField(default=0) created_at = models.DateTimeField(auto_now=datetime.now(), null=True) updated_at = models.DateTimeField(auto_now=datetime.now(), null=True) class Meta(): db_table = 'auth_user_profile' verbose_name = 'User Profile' verbose_name_plural = 'User Profiles' ModelForm : forms.py class CreateUserProfileForm(ModelForm): user = forms.CharField( max_length=25, widget=forms.HiddenInput(attrs={'class': 'form-control', 'id': 'user', }), required=False, ) first_name = forms.CharField( max_length=25, widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'first_name', }), required=True, ) last_name = forms.CharField( max_length=100, widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'last_name', }), required=False, ) dob = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'dob', 'type': 'date', }), required=False, ) username = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'username', }), required=True, ) email = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'email', 'type': 'email'}), required=True, ) password = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'password', 'type': 'password', }), required=True, ) cfm_password = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'cfm_password', 'type': 'password', }), required=True, ) class Meta: model = AuthUserProfile fields … -
How to speed up writing in a database?
I have a function which search for json files in a directory, parse the file and write data in the database. My problem is writing in database, because it take around 30 minutes. Any idea how can I speed up writting in a database? I have few quite big files to parse, but parsing the file is not a problem it take around 3 minutes. Currently I am using sqlite but in the future I will change it to PostgreSQL. Here is my function: def create_database(): with transaction.atomic(): directory = os.fsencode('data/web_files/unzip') for file in os.listdir(directory): filename = os.fsdecode(file) with open('data/web_files/unzip/{}'.format(filename.strip()), encoding="utf8") as f: data = json.load(f) cve_items = data['CVE_Items'] for i in range(len(cve_items)): database_object = DataNist() try: impact = cve_items[i]['impact']['baseMetricV2'] database_object.severity = impact['severity'] database_object.exp_score = impact['exploitabilityScore'] database_object.impact_score = impact['impactScore'] database_object.cvss_score = impact['cvssV2']['baseScore'] except KeyError: database_object.severity = '' database_object.exp_score = '' database_object.impact_score = '' database_object.cvss_score = '' for vendor_data in cve_items[i]['cve']['affects']['vendor']['vendor_data']: database_object.vendor_name = vendor_data['vendor_name'] for description_data in cve_items[i]['cve']['description']['description_data']: database_object.description = description_data['value'] for product_data in vendor_data['product']['product_data']: database_object.product_name = product_data['product_name'] database_object.save() for version_data in product_data['version']['version_data']: if version_data['version_value'] != '-': database_object.versions_set.create(version=version_data['version_value']) I will appreciate if you can give me any advice how can I improve my code. -
My comment reply function is not working well?
I am making a blog but I am stuck on a comment replies function. I don't know how to make a Reply function from which users can reply to the comments. I tried a lot but it's still displaying those comments like other comments not as replies to that specific comment. Here,s the models.py class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name = "comments") name = models.CharField(max_length = 200) body = models.TextField(default = True) pub_date = models.DateTimeField(auto_now_add = True) reply = models.ForeignKey('Comment',null = True,blank = True,on_delete=models.CASCADE) class Meta: ordering = ['-pub_date'] def __str__(self): return self.name @property def get_replies(self): return self.replies.all() class Reply(models.Model): post = models.ForeignKey(Comment,on_delete=models.CASCADE,related_name = "replies") name = models.CharField(max_length = 200) body = models.TextField(default = True) Here's the views.py def BlogDetail(request,pk): post = get_object_or_404(Post,pk = pk) comment = CommentForm(request.POST or None) subscribe = Subscribe() reply = ReplyForm(request.POST or None) if request.method == 'POST': subscribe = Subscribe(request.POST) comment = CommentForm(request.POST) reply = ReplyForm(request.POST) if comment.is_valid(): comment.instance.post = post comment.save() elif subscribe.is_valid(): subscribe = subscribe.save(commit = True) return redirect('index') elif reply.is_valid(): reply.instance.com = com reply = reply.save(commit = True) return redirect('index') return render(request,'app/blog.html',{'blog_object':post,'comment':comment, 'subscribe':subscribe,'reply':reply, }) Here,s the blog.html <form method='POST' action="."> {%csrf_token%} <div class="row"> <div class="col-xs-12 col-sm-12 col-md-4"> <div class="col-inner ts-20 m-sm"> <input type="submit" … -
Django, how to create unique number with specific number
I would like to create unique 5 digit number (id_number) for profile given that the first two is the year that students start study. For example, students enrolled in 2019 have to have id starting with 19 in the first two and random number for other three digits. Thank for all solutions -
how to store in the database the value of choicefiled in model using django
i have a form that allow user to enter a new record to the database by filling the text fields and choose one of the radio button. the system work as it should and save the data of the text field except the radio button where its always empty. Yet if i print the radio button value its printed correctly. models.py class Person(models.Model): boolChoice = ( ("M","Male"),("F","Female") ) name = models.CharField(max_length=50) date = models.DateField() description = models.TextField() gender = models.CharField(max_length = 1,choices=boolChoice) def __str__(self): return str(self.name) addPerson.html {% extends 'base.html' %} {% block content %} <div class="hero__content"> <form method="POST" class="form-style-9">{% csrf_token %} {{ form.as_p }} <ul> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <li> <h2>Add Member</h2> </li> <li> <input type="text" name="name" class="field-style field-split align-right" placeholder= "enter ur name " id="name"/> </li> <li> <input type="date" name="date" class="field-style field-full align-none" placeholder= " your birthdate" id="birthdate" /> </li> <li> <input type="radio" name="gender" value="male"> Male<br> <input type="radio" name="gender" value="female"> Female<br> </li> <li> <textarea name="description" class="field-style" placeholder= "introduce yourself " id="description"></textarea> </li> <li> <input type="submit" class="field-style field-full align-none" id="save" value="ADD" /> <script type="text/javascript"> $(function(){ $('#save').on('click',function(e){ e.preventDefault() name=$('#name').val() birthdate=$('#birthdate').val() description=$('#description').val() radioValue = $("input[name = 'gender']:checked").val() if (radioValue){ alert("radioValue =", radioValue) } $.ajax({ url:'/addperson/', method:'POST', data: { na:name, bi:birthdate, de:description, ra:radioValue … -
Django: constrain foreign key to only rows with the same id
For a Django project, I got two models: class User(AbstractUser): child = models.ForeignKey('children.Child', null=True, on_delete=models.SET_NULL) And the following: class Child(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) What I want is that User.child can only be set to an entity that has child.user_id = user.id, with a constraint preferably. Is this possible? If it matters, I am using PostgreSQL -
Chaining update and get method in Django for updating fields
I have a Django Model as follows: class IPGroup(models.Model): name = models.CharField(max_length=50, unique=True) junos_space_id = models.CharField(max_length=50) class Jira(models.Model): jira_id = models.CharField(max_length=50, unique=True) ip_groups = models.ForeignKey(IPGroup, null=True, on_delete=models.SET_NULL) Now I have a atomic ORM transaction as follows: try: with transaction.atomic(): IPGroup.objects.filter(id=2).update(junos_space_id=3) Jira.objects.filter(jira_id=2)).update(ip_groups_id=2) except Exception: response = Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR, data={'status': 'Database error encountered'}) This works well when everything is fine.However, when an error occurs as in case of an wrong id, filter just gives an empty queryset and it never hits the exception. I tried re-writing it with a get instead of a filter as follows: try: with transaction.atomic(): IPGroup.objects.get(id=2).update(junos_space_id=3) Jira.objects.get(jira_id=2)).update(ip_groups_id=2) except Exception: response = Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR, data={'status': 'Database error encountered'}) But is gives me the following attribute error: AttributeError: 'IPGroup' object has no attribute 'update' What is the best way to doing this in a clean way ? -
Configure Django/Celery to send tasks to different broker
The system is running a Django server (1.11.5) with Celery (4.0.0) and RabbitMQ as broker. It is necessary to send some tasks to a remote server to be processed there. This new server will have its own RabbitMQ installed to use it as broker. The problem comes when on the server where Django is running we need to select which of the tasks keep running on the local machine and which are sent to the new server. Due to some architecture reasons is not possible to solve this using queues, tasks must be sent to the new broker. Is it possible to create two different Celery apps in Django (each one pointing to a different broker) which their own tasks each one? How can it be done? -
Django Rest Framework override viewset list method optionally?
I am trying to modify the list method of a ViewSet. I need to return data only if a condition satisfies. otherwise the default behaviour should be invoked. def list(self, request): """Allow profile listing only for admin and super admins.""" if request.user.is_authenticated and request.user.user_type == constants.Constants.ADMIN: #invoke default behaviour pass else: return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED) But this code does not work in case the condition passes. I'm new to Django and DRF, is there a better way to do this? Or how can I fix the above code? -
build When Case query in for loop django
i try build queryset for update data with When Case. It only can build after one for loop. Example i have model Employee: class Employee(models.Model): account_type = models.TextField(blank=True, null=True) i want update it like this, if id = 1 then value = 1, if value = 2 then value = 2 Employee.objects.update( account_type=Case( When(id=1, then=Value("1")), When(id=2, then=Value("2")), ), ) but i want id is dynamic, so i cant build static queryset. I want build Case in one for loop. My ideal like this: final_case = None for one_id in list_id: final_case += Case(When(id=one_id, then=Value(one_id))) I want build final_case and update only like Employee.objects.update(account_type=final_case) Anybody know how to do it ? Thanks -
DRF: viewsets lookup_field ImproperlyConfigured
I'm migrating my DRF from generics to viewsets, but I receive this error: Could not resolve URL for hyperlinked relationship using view name "monument-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. This is my urls.py from app.api import views from rest_framework import routers router = routers.DefaultRouter() router.register(r'monuments', views.MonumentsViewSet) urlpatterns = router.urls This is my viewset from app.api import serializers from rest_framework import viewsets class MonumentsViewSet(viewsets.ModelViewSet): serializer_class = serializers.MonumentSerializer queryset = serializer_class.Meta.model.objects.all() lookup_field = 'id' And finally here my serializer from app.api import models from rest_framework import serializers class MonumentSerializer(serializers.HyperlinkedModelSerializer): images = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='monument-detail') class Meta: model = models.Monument fields = '__all__' -
How to fix tests after Django 1.10 to 1.11 update
I'm working on a project that uses Django 1.10 and DRF. When I upgrade Django to 1.11, many tests in classes that inherit from DRF's APITestCase fail with the following error: AttributeError: 'HttpResponseBadRequest' object has no attribute 'data' In Django 1.10, however, if I try to access an non-existing attribute of the response, I get: AttributeError: 'Response' object has no attribute 'ariel' DRF's test client extends Django's test client, so I suppose that class changed its interface from 1.10 to 1.11 and is doing some magic and returning an instance of this new HttpResponseBadRequest class, which doesn't have a "data" attribute. However, I didn't find these changes documented anywhere and I didn't find any discussion online proposing a solution for this. Does anybody have any idea what has to be changed and where I can find documentation for the new test client interface? -
when i use Materialize than checkbox field not showing in html page in django forms
I am working on quiz app, and I am using Django for back-end and Materialize for front-end. in questionchange view function using inlineformset_factory in answer model model.py class Answer(models.Model): question = models.ForeignKey(QuestionModel, on_delete=models.CASCADE, related_name='answers') text = models.CharField('Answer', max_length=255) is_correct = models.BooleanField('Correct answer', default=False) def __str__(self): return self.text forms.py class BaseAnswerInlineFormSet(forms.BaseInlineFormSet): DELETE =forms.BooleanField() is_correct =forms.BooleanField() def clean(self): super().clean() has_one_correct_answer = False for form in self.forms: if not form.cleaned_data.get('DELETE', False): if form.cleaned_data.get('is_correct', False): has_one_correct_answer = True break if not has_one_correct_answer: raise ValidationError('Mark at least one answer as correct.', code='no_correct_answer') views.py def question_change(request, question_pk): question = get_object_or_404(QuestionModel, pk=question_pk) AnswerFormSet = inlineformset_factory( QuestionModel, # parent model Answer, # base model formset=BaseAnswerInlineFormSet, fields=('text', 'is_correct'), min_num=2, validate_min=True, max_num=8, validate_max=True ) if request.method == 'POST': form = QuestionForm(request.POST, instance=question) formset = AnswerFormSet(request.POST, instance=question) if form.is_valid() and formset.is_valid(): with transaction.atomic(): form.save() formset.save() messages.success(request, 'Question and answers saved with success!') return redirect('questions:question_list') else: form = QuestionForm(instance=question) formset = AnswerFormSet(instance=question) return render(request, 'question/question_change_form.html', { 'question': question, 'form': form, 'formset': formset }) uestion_change_form.html enter image description here output - with basefile showing like thiswith base.html showing like this and checkbox not showing without base.html showing checkbox checkbox showing here -
How to use Masquerade in Dj ango 1.11+
Masquerade option is no longer supported in Django 1.11 , so what is the alternative to it ? Any known fix available for it ? -
Why give in firefox I get error:'no such table: django_session' on /server/admin/, in chrome it works
I start with Django 2.0.2 course. I discovered that in chrome I get on http://127.0.0.1:8000/ the Django Home page, in Firefox Dev. as well. On opening http://127.0.0.1:8000/admin in chrome it works as expected http://127.0.0.1:8000/admin/login/?next=/admin/. However in firefox I get 'no such table: Django_session'. I work in Windows 10, virtualenv created by pipenv. What is wrong? -
django wagtail add page by site id
enter code hereI made a class in home/models.py to create page and add to specific site in wagtail cms admin interface depending on site id same as documentation https://docs.djangoproject.com/en/2.1/ref/contrib/sites/ also i'm inheriting MenuPage inside the class to use sub menu but when i made migration i got error of page inherit even if i change the inheritance. help please? from django.db import models from django.contrib.sites.models import Site from django.contrib.sites.managers import CurrentSiteManager from django.utils import translation # New imports added for ParentalKey, Orderable, InlinePanel, ImageChooserPanel from modelcluster.fields import ParentalKey from wagtail.core.models import Page, PageManager, Orderable from wagtail.core.fields import RichTextField from wagtail.admin.edit_handlers import FieldPanel, MultiFieldPanel, InlinePanel from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.search import index from wagtailmenus.models import MenuPage from wagtailmenus.panels import menupage_panel class TranslatedField(): def __init__(self, en_field, sv_field): self.en_field = en_field self.sv_field = sv_field def __get__(self, instance, owner): if translation.get_language() == 'sv': return getattr(instance, self.sv_field) else: return getattr(instance, self.en_field) class HomePage(MenuPage): body = RichTextField(blank=True) site = models.ForeignKey(Site, on_delete=models.CASCADE) objects = models.Manager() on_site = CurrentSiteManager() content_panels = MenuPage.content_panels + [ FieldPanel('body', classname="full"), FieldPanel('site'), ] class HomeOnePage(MenuPage): body = RichTextField(blank=True) site = models.ForeignKey(Site, on_delete=models.CASCADE) objects = models.Manager() on_site = CurrentSiteManager() content_panels = MenuPage.content_panels + [ FieldPanel('body', classname="full"), FieldPanel('site'), ] class BlogIndexPage(MenuPage): intro = RichTextField(blank=True) … -
Django DateTimeField() casuing TypeError ('datetime.timedelta' object is not callable)
I am trying to get differenc of two Datetiemfield in Djago. I have tried overriding the default save() but still getting error. models.py class Sample(models.Model): ad_start = models.DateTimeField() ad_end = models.DateTimeField() ad_duration = models.IntegerField() @property def get_time_diff(self): timediff = self.ad_end - self.ad_start return timediff #return relativedelta(self.ad_end, self.ad_start) def save(self, *args, **kwargs): self.ad_duration = self.get_time_diff() super(Sample, self).save(*args, **kwargs) forms.py class SampleForm(forms.ModelForm): class Meta: model = Sample exclude = ("submitted", 'ad_duration', "list_date" ) widgets = { 'ad_start': DatePickerInput(), 'ad_end': DatePickerInput(), } Error Django Version: 2.1.7 Exception Type: TypeError Exception Value:'datetime.timedelta' object is not callable -
Django: Global modification of readonly field appearance
I want to customize the field texture in django’s new “readonly mode”: E.g. foreign keys shall be displayed as links. In general I identified the following options: Implement custom fields for every model – results in code duplication Reimplement django’s display_for_field method Basically I could copy & paste the django.contrib.admin.utils module, insert my changes, override sys.modules['django.contrib.admin.utils'] = myutils but that's ugly because of maintainability in case of Django updates in the future. So I decided to override only the display_for_fields method of django.contrib.admin.utils using the following approach to avoid duplication of Django code: Override display_for_field function in django.contrib.admin.utils in settings.py: from myapp.contrib.admin import utils utils.override_method() In myapp.utils.py: from django.contrib.admin import utils from django.contrib.admin.utils import * def display_for_field_mod(value, field, empty_value_display): if isinstance(field, models.ForeignKey) and value: if field.related_model.__name__.lower() != 'user': link_string = 'admin:myapp_' + field.related_model.__name__.lower() + '_change' link = reverse(link_string, args=(value.id,)) return format_html('<a href="{}">{}</a>', link, value) else: return formats.localize(value) else: return display_for_field(value, field, empty_value_display) def override_method(): utils.display_for_field = display_for_field_mod But the problem is: display_for_field gets imported in django.contrib.admin.helpers using: from django.contrib.admin.utils import ( display_for_field, [...] ) So due to the scope of the imported funtion I cannot override this function from outside. Do I miss some other obvious possibility? Is there a … -
TransactionManagementError during call of `response_change`
I'm working on Django 1.8 project, which has reach feature set in admin part. One of the ModelAdmin subclass overrides response_change method to handle action for APPROVE button. So, the code looks like the following: class MyModelAdmin(ModelAdmin): def response_change(self, request, obj): rel = obj.rel rel.title = obj.title rel.save() serialize('json', (rel, )) obj.approved = true obj.save() return super().response_change(request, obj) And I'm getting the error on serialization line: File "/env/lib/python3.6/site-packages/django/core/serializers/__init__.py", line 129, in serialize s.serialize(queryset, **options) File "/env/lib/python3.6/site-packages/django/core/serializers/base.py", line 68, in serialize self.handle_m2m_field(obj, field) File "/env/lib/python3.6/site-packages/django/core/serializers/python.py", line 77, in handle_m2m_field for related in getattr(obj, field.name).iterator()] File "/env/lib/python3.6/site-packages/django/core/serializers/python.py", line 76, in <listcomp> self._current[field.name] = [m2m_value(related) File "/env/lib/python3.6/site-packages/django/db/models/query.py", line 238, in iterator results = compiler.execute_sql() File "/env/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 840, in execute_sql cursor.execute(sql, params) File "/env/lib/python3.6/site-packages/django/db/backends/utils.py", line 59, in execute self.db.validate_no_broken_transaction() File "/env/lib/python3.6/site-packages/django/db/backends/base/base.py", line 327, in validate_no_broken_transaction "An error occurred in the current transaction. You can't " django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. If I remove serialization line - the same error appears on obj.save() line. And the most strange part is that such … -
how to get the value of checked radio button using django and jquery
i have a simple form that includes text fields and radio buttons where the system take the user input and add new record to the database. the problem that once the user fill the form and click on submit button the system display the below error: return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: NOT NULL constraint failed: map_person.gender models.py class Person(models.Model): boolChoice = ( ("Male","M"),("Female","F") ) name = models.CharField(max_length=50) date = models.DateField() description = models.TextField() gender = models.BooleanField(choices= boolChoice) def __str__(self): return str(self.name) addPerson.html {% extends 'base.html' %} {% block content %} <div class="hero__content"> <form method="POST" class="form-style-9">{% csrf_token %} {{ form.as_p }} <ul> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <li> <h2>Add Member</h2> </li> <li> <input type="text" name="name" class="field-style field-split align-right" placeholder= "enter ur name " id="name"/> </li> <li> <input type="date" name="date" class="field-style field-full align-none" placeholder= " your birthdate" id="birthdate" /> </li> <li> <input type="radio" name="gender" value="male"> Male<br> <input type="radio" name="gender" value="female"> Female<br> </li> <li> <textarea name="description" class="field-style" placeholder= "introduce yourself " id="description"></textarea> </li> <li> <input type="submit" class="field-style field-full align-none" id="save" value="ADD" /> <script type="text/javascript"> $(function(){ $('#save').on('click',function(e){ e.preventDefault() name=$('#name').val() birthdate=$('#birthdate').val() description=$('#description').val() radioValue = $("input[name = 'gender']:checked").val() if (radioValue){ alert("radioValue =", radioValue) } alert("name =", name) alert("date =", birthdate) alert("desc =", description) $.ajax({ url:'/addperson/', method:'POST', data: { …