Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Custom function which performs create and update on DRF modelViewSet
Hi there i have two models the Heat and Breeding. I want to create a custom method in a modelviewset which needs to perform a save and an update logic. Here is my breeding.viewsets.py class BreedingViewSet(viewsets.ModelViewSet): queryset = Breeding.objects.all() serializer_class = BreedingSerializer Since the above method has a higher level of abstraction and is actually providing or performing automatic CRUD functions. Now the problem here is i dont have any control for a multiple transaction like saving an object and updating another object in a single function. e.g @transaction.atomic() def save_and_update(self, request): do save breeding here. do update a heat here. This is my heat.models.py class Heat(models.Model): # Fields performer = models.CharField(max_length=25) is_bred = models.BooleanField(default=False) note = models.TextField(max_length=250, blank=True, null=True) This is my breeding.model.py class Breeding(models.Model): # Relationship Fields heat = models.OneToOneField( Heat, on_delete=models.CASCADE) # Fields performer = models.CharField(max_length=25) remarks = models.TextField(max_length=255, blank=True, null=True) How can we achieve such powerful functionalities? Did i missed something? I found this documentation but i dont know how to implement the given instruction. -
Using RenderContext in render_to_string in Django 1.10
I'm upgrading a project to Django 1.10 and trying to change the following template tag (simplified) @register.simple_tag(takes_context=True) def render_svg(context, svg_template_file_name, *args, **kwargs): svg_string = render_to_string(svg_template_file_name, context, request=context.request) This no longer works since the context passed in is a RenderContext, where the docs state: If you’re passing a Context in context_instance, pass a dict in the context parameter instead. If you’re passing a RequestContext, pass the request separately in the request parameter. Which I'm already doing and still would like to make use of the context parameter to render_to_string... So how can I get a usable dictionary from a RenderContext? -
How can I test that I got back a MagicMock that I injected?
Here is a little class (in myapp/getters.py): from django.contrib.auth.models import User class UserGetter: def get_user(self): return User.objects.get(username='username') I would like to mock out the call to User.objects.get, return a MagicMock, and test that the method returns what I injected. In myapp/tests/tests_getters.py: from unittest import TestCase from django.contrib.auth.models import User, UserManager from mock import patch, create_autospec from myapp.getters import UserGetter class MockTestCase(TestCase): @patch('myapp.getters.User', autospec=True) def test(self, user_class): user = create_autospec(User) objects = create_autospec(UserManager) objects.get.return_value = user user_class.objects.return_value = objects self.assertEquals(user, UserGetter().get_user()) But when I run this test (with python manage.py test myapp.tests.tests_getters) I get AssertionError: <MagicMock name='User.objects().get()' spec='User' id='4354507472'> != <MagicMock name='User.objects.get()' id='4360679248'> Why do I not get back the mock I injected? How can I write this test correctly? -
Provide different kwargs for each form in formset
I am trying to use a formset to create forms for a set of timeframes related to dates: class Event(models.Model): date = models.DateField() class TimeFrame(models.Model): start = models.DateTimeField() end = models.DateTimeField() event = models.ForeignKey('Event') I have code that gets me a queryset of timeframes for each event and added a kwarg to pass this into my form: class SelectDatesForm(forms.Form): timeframes = forms.ModelChoiceField(queryset=HostTimeFrame.objects.none()) def __init__(self, *args, **kwargs): qs = kwargs.pop('timeframes') super(SelectDatesForm, self).__init__(*args, **kwargs) self.fields['timeframes'].queryset = qs Now I'm trying to construct a formset that lets me show timeframes for multiple events on one page. I already found this question, explaining how to pass initial data, for serveral forms, but its not the same as passing it to a queryset. Also there is this new function from django 1.9 but it doesnt allow me to get different querysets for each form. -
Django Models with Choices as Integer
I am trying to make a feedback app in Django, but I can not make my evaluations. In my models.py, I have 5 choices from very bad to excellent. But I want them to be usable as numbers so I can evaluate the overall value. After reading Set Django IntegerField by choices=... name I changed my Ratings from VERYBAD = 'Very bad' to VERYBAD = 1 but no I can't even save my value/form. Feedback(models.Model): event = models.ForeignKey(Event) # Choice VERYBAD = 'Very bad' #old BAD = 2 #new OKAY = 3 GOOD = 4 EXCELLENT = 5 RATING = ( (VERYBAD, 'Very bad'), (BAD, 'Bad'), (OKAY, 'Okay'), (GOOD, 'Good'), (EXCELLENT, 'Excellent'), ) # The ratings organisation = models.CharField( max_length=9, choices=RATING, default=OKAY, ) .... So in my view, I thought I can do the math but I can not. def rating(request, event_id): myevent = Event.objects.get(id=event_id) feedback_items = Feedback.objects.filter(event=myevent) num_of_items = len(feedback_items) def evaluate(feedback_items): # The overall rating organisation = 0 for item in feedback_items: organisation += item.organisation organisation /= num_of_items context = {'feedback_items':feedback_items, 'num_of_items': num_of_items, 'myevent': myevent,} return render(request, 'feedback/rating.html', context) ` -
Simple Django Reverse URL with Parameters not working
I can't figure out why this one scenario of using {% url %} with parameters in this template is tripping me up. I've done it before and it worked fine but I can't find what's wrong with this code. urls.py url(r'^promotions/$', views.promotions, name="promotions"), url(r'^promotions/(?P<title>[-\w]+)/$', views.promotion_detail, name="promotions_detail"), promotion.html {% for promotion in promotions %} <div class="a-promotion"> <div class="column-1"> <div class="title">{{promotion.title}}</div> <div class="offer">{{promotion.amount}}</div> </div> <div class="column-2"> **********THE LINE BELOW THROWS THE ERROR****************** {{promotion.short_description}}... <a href="{% url 'promotions_detail' title=promotion.title %}"><span class="learn-more">Learn More</span></a> </div> </div> {% endfor %} Error: NoReverseMatch at /promotions/ Reverse for 'promotions_detail' with arguments '()' and keyword arguments '{u'title': u'Welcome to Our Site'}' not found. 1 pattern(s) tried: ['promotions/(?P<title>[-\\w]+)/$'] -
Ionic 2 pass photo to object field on Django rest api
I'm looking for solution. I have an rest api on Django and Ionic2&Angular2 app. Mayby somebody know how I can create a object on server an add a file from phone (photo) to the object in database. I search a lot of but not figured how to do this. Maybe somebody have any example or useful Tips. Thank you very much for any aswers :) -
Handling JavaScript testing for VanillaJS, dropzone.js and Django project
I'm working on a project that at this point mostly involves custom code written in VanillaJS to communicate with a Django backend. I'm very new to software testing in general, so I am a bit at a loss as to how to best handle unit testing or generally just testing the JavaScript code I've written. Is there even a case for unit testing here, because currently I mostly just hook to different dropzone.js event handlers and get my code ran. For example, there's this: custom_dropzone.on('removedfile', function(file) { removeFileFromServer(file); }); or this: custom_dropzone.on('success', function(file, response) { file.id = response.id; }); The removeFileFromServer(file) function is something that surely COULD be unit tested, but it would require a lot of digging in the original dropzone.js code to get all the necessary attributes right for 'file' and then a way to trigger it. The backend is at the time quite extensively tested and I trust that if anything strange starts to happen, it will be quickly caught in either the backend test suite or by exploratory testing. Maybe Selenium and functional tests could be a better way forwards? I feel I've been so deeply convinced to "test all the things" by what I've read … -
Adding SSL certificates to a mysql docker container
I am building a docker container for a django application, which uses nginx and uwsgi. For the Database the application is using mysql, which is located in a different container and both of them are link with a docker-compose.yml file: version: '2' services: mysql: image: mysql:latest environment: -MYSQL_DATABASE: TheDatabase -MYSQL_ALLOW_EMPTY_PASSWORD: 'yes' -MYSQL_USER: TheUsername -MYSQL_PASSWORD: ThePassword ports: -"3306:3306" django: build: . volumes: - .:/app ports: - "443:443" - "8000:8000" links: - mysql I am using SSL certificates, which are self-signed using OpenSSL and are included in the nginx.conf file. The problem is that every time I run the containers and try to log as the superuser I get the following error 504 Timed Out. After a decent amount of thinking I came to the conclusion that the issue is in the connection to the mysql database. I did enter the mysql container and saw that the Database is there and after inspecting the tables, I saw that all the tables have been created. However, after reading the logs I noticed the following line: [Warning] Failed to set up SSL because of the following SSL library error: SSL context is not usable without certificate and private key. How am I supposed to … -
Django web page- how to manipulate what information is displayed in a table
I have a Django project, and one of my views renders a page that displays a table with information about objects in the database. The objects displayed differ based on the criteria determined in the view. The if statement used in the view to determine which page to render is: if request.GET.get('stage') == 'pd': """ Render post deposit homepage """ print "request.GET.get('stage') == 'pd' " print "render_to_string() called with parameter: costing/report2_ccis.html" context['html'] = render_to_string('costing/report2_ccis.html', context) context['active_tab'] = '4' if(project.deposit_received == True): print "costing/reports_post_deposit.html is the page being rendered (project.deposit_received = true)... " return render(request, 'costing/reports_post_deposit.html', context) elif(project.deposit_received == False): print "costing/reports_pre_deposit.html is the page being rendered (project.deposit_received = False)..." return render(request, 'costing/reports_pre_deposit.html', context) else: """ Render pre deposit homepage """ print "request.GET.get('stage') != 'pd' " print "render_to_string() called with parameter: costing/report_ccis.html" context['html'] = render_to_string('costing/report_ccis.html', context) context['active_tab'] = '5' if(project.deposit_received == True): print "costing/reports_post_deposit.html is the page being rendered (project.deposit_received = true)..." return render(request, 'costing/reports_post_deposit.html', context) elif(project.deposit_received == False): print "costing/reports_pre_deposit.html is the page being rendered (project.deposit_received = false)..." return render(request, 'costing/reports_pre_deposit.html', context) Both of the templates returned in the view extend another template called reports_tabbed.html, and the report_ccis.html & report2_ccis.html templates that are passed to the render_to_string view both extends … -
Use Django model IntegerField validator values on the form
I am able to set the minimum value validator on the model: class MyModel(Model): my_field = models.fields.IntegerField(default=250, validators=[MinValueValidator(30)]) Then I create a form using the previous model: class MyForm(ModelForm): class Meta: model = MyModel fields = ('my_field',) The form gets validated, the correct error message is displayed (when entered value is <30), but even when entered wrong value, it gets saved on the instance! I was able to make it work by specifying (again) the min value on the form: class MyForm(ModelForm): my_field = form.IntegerField(min_value=30) class Meta: model = MyModel fields = ('my_field',) But this way the code is not dry - I need to specify the value and field type twice. Is there any way I could avoid this? Or at least get the min_value from the model validator? -
Jquey Autocomplete - post data after selected
I using Djago + jquery autocomplete. The auto complete is indeed working. But I am not sure how to send the data after the user select it. When I send it it comes all the info that autocomplete retrieve... Jquery $("#tags5").autocomplete({ minLength:3, source: function(req, add){ var search=$("#tags5").val(); $.ajax({ url:'/ajax/', async:false, dataType:'json', type:'GET', data:{ 'start': search,}, success: function(data){ var suggestions=[]; $.each(data, function(index, objeto){ suggestions.push(objeto); }); add(suggestions); #send data $.get( "/showlist", { suggestions }); }, error:function(err){ alert("error"); } }); } }); }); html <form id='tv' method="GET" action="/showlist">{% csrf_token %} <label for="tags5"> </label> <input id="tags5" style="width: 500px"> <button class='btn btn-conf btn-green' type="submit" id="post-btn" style="width: 200px" >Adicionar</button> </form> Output: [06/Dec/2016 13:53:40] "GET /showlist?suggestions%5B0%5D%5Bvalue%5D=Dancing+with+the+Stars&suggestions%5B0%5D%5Blabel%5D=Dancing+with+the+Stars&suggestions%5B1%5D%5Bvalue%5D=Dance+Moms&suggestions%5B1%5D%5Blabel%5D=Dance+Moms&suggestions%5B2%5D%5Bvalue%5D=Dancing+on+the+Edge&suggestions%5B2%5D%5Blabel%5D=Dancing+on+the+Edge&suggestions%5B3%5D%5Bvalue%5D=So+You+Think+You+Can+Dance&suggestions%5B3%5D%5Blabel%5D=So+You+Think+You+Can+Dance&suggestions%5B4%5D%5Bvalue%5D=Dance+Academy&suggestions%5B4%5D%5Blabel%5D=Dance+Academy HTTP/1.1" 200 80211 [06/Dec/2016 13:53:45] "GET /showlist?csrfmiddlewaretoken=VaD6qQEWFViTSV1wvI3cNWGARSqZRnxYXeB3bwWsfxyzTBQv1SJ4oN4Yqeny2fMf HTTP/1.1" 200 80211 I should get only the Dance Moms options for example, instead it is bring all of them. I tried to use the change and selector events but it didnt work either... -
Django: assertEqual(response.status_code, 200): I want to see useful traceback
If I use the django testing web client like this, I get a useless traceback: def test_details(self): # Issue a GET request. response = self.client.get('/customer/details/') # Check that the response is 200 OK. self.assertEqual(response.status_code, 200) Source: https://docs.djangoproject.com/en/1.10/topics/testing/tools/#example It's useless for me, since I see the traceback of the assertEqual() method. A useful traceback for me in this context would show me the traceback where the Response with the unexpected status_code was created. How could this be done? -
Get block content from a template
I' ve a template file containing several blocks, but how can i get the content of one of the views? For instance: {% extends "base.txt" %} {% block subject %}Sub1{% endblock %} {% block body %}Bod1{% endblock %} . Is there any way to get only the content of the subject block? -
Django Partial mocking implementation
I wrote an unit test for attendance system written in python. It checks that NAT (not assigned time) is updated over time. In the test I have to wait for change in the NAT. Sleep method was used, but I am not happy with this solution. NAT is calculated with use of datetime.now(). I tried to mock datetime.now() with partial mock like in the link: https://docs.python.org/3/library/unittest.mock-examples.html#partial-mocking It is error free, but the time delay is not created. tests.py and models.py are in same folder Python 3.5.2, Django 1.10.3 tests.py code: .... from .models import Session from datetime import datetime, timedelta from django.utils import timezone from unittest.mock import patch class SessionTestCase(TestCase): .... def test_NAT_value_of_opened_session_is_updated_overtime_if_IN_swipe_is_corrected(self): user1 = UserFactory() swipe1 = SwipeFactory(user = user1, swipe_type = "IN") swipe2 = SwipeFactory( # correction of swipe1 user = user1, swipe_type = "IN", correction_of_swipe = swipe1, datetime = swipe1.datetime + timedelta(seconds = 1), ) nat_1 = swipe2.session.get_not_assigned_duration() with patch('attendance.models.datetime') as mock_date: mock_date.now(timezone.utc).return_value = datetime.now(timezone.utc) + timedelta(seconds = 1) mock_date.side_effect = lambda *args, **kw: date(*args, **kw) nat_2 = swipe2.session.get_not_assigned_duration() self.assertNotEqual(nat_1, nat_2) .... models.py code: .... from django.db import models from datetime import datetime, timezone, timedelta .... class Session(models.Model): .... def session_duration_overall(self): .... end_datetime = datime.now(timezone.utc) return end_datetime … -
Docker linking failure with nginx
Trying desperately to dockerize my Django app. I'm trying to use nginx as reverse proxy as it is suggested on many sources. version: '2' services: db: build: ./MongoDocker image: okidocky_mongo ports: - 27017:27017 volumes: #making user related path on localhost mounted in /data - ~/Desktop/Documents/DB:/data networks: okidocky_net: ipv4_address: 10.0.0.11 #TODO: Set environment file. web: restart: always build: ./DjangoDocker image: okidocky volumes: - /var/www/html/project/website/okidocky_project ports: - 8001:8000 links: - db:db networks: okidocky_net: ipv4_address: 10.0.0.10 nginx: restart: always build: ./nginx image: okidocky_nginx ports: - 80:80 volumes: - /var/www/static volumes_from: - web links: - web:web networks: okidocky_net: driver: bridge # driver_opts: # com.docker.network.enable_ipv6: "true" driver_opts: com.docker.network.enable_ipv4: "true" ipam: driver: default config: - subnet: 10.0.0.0/16 gateway: 10.0.0.1 My docker file has been cloned by this article: FROM tutum/nginx RUN rm /etc/nginx/sites-enabled/default ADD sites-enabled/ /etc/nginx/sites-enabled as well as the configuration for nginx. Just changed the door to 8001 as "web" is mapped on that server { listen 80; server_name example.org; charset utf-8; location /static { alias /var/www/html/project/website/ockidocky_project; } location / { proxy_pass http://web:8001; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } When I look at docker logs ockidockydocker_nginx_1 I only read this. nginx: [emerg] host not found in upstream I thought it … -
How to add custom, non-model fields dynamically to Django ModelAdmin or ModalForm?
I am trying to create custom fields for my modal in Django Admin. I have two models - Page and PageTemplate. PageTemplate stores all the needed custom fields for the Page and has a property custom_fields = JSONField(default={}). Page has a OneToOne relationship to PageTemplate. Page also has a custom_fields = JSONField(deafult={}). This property stores the values for the page. Here is my admin and form signature: class PageAdmin(TranslatableAdmin): form = PageForm fields = ['title', 'slug', 'body', 'parent', 'template', 'test'] class PageTemplateAdmin(admin.ModelAdmin): search_fields = ['name', 'slug'] list_display = ['name', 'slug'] fields = ['name', 'slug', 'custom_fields'] class PageForm(TranslatableModelForm): def __init__(self, *args, **kwargs): super(PageForm, self).__init__(*args, **kwargs) if 'instance' in kwargs: instance = kwargs['instance'] if instance.template: custom_fields = instance.template.custom_fields # Add a test field so that it shows it in admin: self.fields['test'] = forms.DateField() class Meta: model = Page exclude = () This system will work in the following way: If a template is given to Page, it will read the custom_fields property of PageTemplate from the OneToOne relationship and display them with the given widgets in Page. Then just get the values from Page's custom_fields property and populate the added Page Template custom_fields with the retrieved data. Before save, these fields will … -
filter model according to DateField and TimeField
I have an Event model like following; class Event(models.Model): name = models.CharField(max_length=50) date = models.DateField(null=True) start = models.TimeField(null=True) location = models.CharField(max_length=255) creator = models.ManyToManyField(User, related_name='event_creator') info = models.CharField(max_length=255, default='') users = models.ManyToManyField(EventUser, blank=True) def __str__(self): return self.name And this is my serializer class EventSerializer(serializers.ModelSerializer): users = UserListingField(many=True, read_only=True) creator = serializers.SlugRelatedField(many=True, read_only=True, slug_field='username') class Meta: model = Event fields = '__all__' But I want to get only the events that is not outdated instead of all the events. How can I achieve this? -
Databinding with Django channel in custom command
I start work with Django channel. I need bind data of my model Device. I do it. When I change Device object in admin interface I get message about changing on client (web brouser) but I also run simple WebsocketServer by means of custom django management command. And when Device-object has been changed in custom command process I don't recive any message on client. How I can fix it? devices/models.py OFFLINE = 0 ONLINE = 1 REGISTRATION = 2 REMOVED = 3 ERROR = 4 STATUS_CHOICES = ( (OFFLINE, _("Offline")), (ONLINE, _("Online")), (REGISTRATION, _("Registration")), (REMOVED, _("Removed")), (ERROR, _("Error")), ) class Device(models.Model): name = models.CharField(max_length=128, null=True, blank=True, default=None, verbose_name=_("Name")) created = models.DateTimeField(verbose_name=_("Creation date time"), editable=False) modified = models.DateTimeField(verbose_name=_("Last change date time"), blank=True) removed = models.BooleanField(verbose_name=_("Device has been removed"), default=False) remove_date = models.DateTimeField(verbose_name=_("Date of Device removing"), null=True, blank=True, default=None) joined = models.BooleanField(verbose_name=_("Registration status"), default=False) date_joined = models.DateTimeField(verbose_name=_("Registration date time"), blank=True, null=True, default=None) owner = models.ForeignKey("accounts.User", null=True, blank=True, default=None, verbose_name=_("Who registered"), on_delete=models.SET(None)) status = models.SmallIntegerField(choices=STATUS_CHOICES, blank=True, default=REGISTRATION, verbose_name=_("Status")) frozen = models.BooleanField(default=False, verbose_name=_("Device is frozen")) devices/databinding.py from channels.binding.websockets import WebsocketBinding from .models import Device class DeviceBinding(WebsocketBinding): model = Device stream = "device" fields = ['status', 'joined', 'frozen'] @classmethod def group_names(cls, *args, **kwargs): return ["binding.devices"] … -
Django REST: Creating db entries in related table in one POST
I have two models, one is pointing to other model. class ModelA(models.Model): field1 = models.CharField() field2 = models.CharField() class ModelB(models.Model): field3 = models.CharField() field4 = models.CharField() modela = models.ForeignKey(ModelA) I am using Django REST for data manipulation. I am trying to insert data to ModelA and ModelB using one ajax call. For one entry in ModelA, I have a list of entries in ModelB. So my ajax data is, ajax_data = {modela: {....}, modelb: [{...}, {...}, ...]} When I am using only one model, I am able to save, otherwise I am not. Can I save two related model in one one POST request? -
Unable to upload file via Python Django 1.10.3
Currently trying to create a small file upload system similar to what was done here I've been trying to get my code to let the user upload any file from their local PC and then let it be copied to my server. albeit with no luck, the example I was following has examples up to 1.9 Django and I can't see much variation with that and 1.10. I've attached my views.py for the project currently the website i have will not upload any type of file and im not sure why from django.shortcuts import render # Create your views here. from django.http import HttpResponseRedirect from django.http import HttpResponse from django.shortcuts import render from django.core.urlresolvers import reverse from .forms import docform from .models import Document def upload(request): if request.method == 'POST': form = docform(request.FILES) if form.is_valid(): newdoc = Document (newfile=request.FILES['newfile']) newdoc.save() return HttpResponseRedirect(reverse('upload')) else: form = docform() return render( request,'upload.html',) -
Django and JSON/AJAX testing
I tried looking around for an answer and gave it a great many tries, but there's something strange going on here. I got some functions in my view that operate on JSON data that comes in via AJAX. Currently I'm trying to do some unit testin on these. In my test case I have: kwargs = {'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'} url = '/<correct_url>/upload/' data = { "id" : p.id } c = Client() response = c.delete(url, data, **kwargs) content_unicode = response.content.decode('utf-8') content = json.loads(content_unicode) p.id is just an integer that comes from a model I'm using. I then have a function that is being tested, parts of which looks like follows: def delete_ajax(self, request, *args, **kwargs): print (request.body) body_unicode = request.body.decode('utf-8') print (body_unicode) body_json = json.loads(body_unicode) The first print statement yields: .....b"{'id': 1}" The other one: {'id': 1} and finally I get an error for fourth line as follows: json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1) What's going wrong here? I understand that correct JSON format should be {"id": 1} and that's what I'm sending from my test case. But somewhere along the way single-quotes are introduced into the mix causing me head ache. Any … -
Related model can not be resolved django error
In my django project when migrate my project is shows me error raise ValueError('Related model %r cannot be resolved' % self.rel.to) ValueError: Related model u'partner.PartnerShop' cannot be resolved What is this problem and why this is happening?? -
Creating users with custom attributes: the post_save signal seems not to be received
I want to create users based on info from a CSV file. My users have two additional attributes, 'pensum' and 'stopien': class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) stopien = models.CharField(max_length=100) pensum = models.IntegerField() This is my import routine: from django.db.models.signals import post_save from django.dispatch import receiver #so that a created user would already have 'stopien' and 'pensum' attributes to be set @receiver(post_save, sender=User) def create_employee(sender, instance, created, **kwargs): if created: Employee.objects.create(user=instance) #row 0 and 1: username; 2: email, 3: stopien, 4: pensum def importusers(filename): dataReader = csv.reader(open(filename), delimiter=str(u';').encode('utf-8'), quotechar=str(u'"').encode('utf-8')) for row in dataReader: if row[0] != 'name': # Ignore the header row, import everything else #the following is the intended username, which at this moment will be used as a password too (will fix this later) uzytkownik=row[0]+row[1] newuser = User.objects.create_user(uzytkownik, row[2], uzytkownik, first_name=row[0], last_name=row[1]) newuser.save() newuser.pensum = row[4] newuser.stopien = row[3] newuser.save() However, the receiver seems never to be invoked: users get created, but without any 'stopien' or 'pensum'. No error is given. What am I doing wrong? (I'm also importing django.db.models.signals at the end of models.py.) -
How to take values from checkboxes row by row from a table and update DB using django
I am trying to get the value of some checkboxes and update database for the rows that are checked. I don’t really know how to do it since I am only starting with Django/python. Here is my model class App_Setting(models.Model): setting_name = models.CharField('Setting Name', max_length=30, unique=True, blank=False, default='None') setting_enab = models.BooleanField('Enabled?', default=False) setting_descr = models.CharField('Description', max_length=150, blank=False, default='None') Because I want the user to only be able to modify the “setting_enab” via checkbox I have built my template like this {% extends "mainapp/base.html" %} {% block title %}- Available Settings{% endblock %} {% block mainframe %} <h3>Available Settings</h3> <div class="col-sm-8 col-lg-9"> <table class="table table-striped table-hover"> <thead> <tr> <th>Setting Name</th> <th>Setting Enabled?</th> <th>Setting Description</th> </tr> </thead> <tbody> {% for setting in object_list %} <tr> <td>{{ setting.setting_name }}</td> <td><input type="checkbox" name="mycheckbox" class="checkthis" /></td> <td>{{ setting.setting_descr }}</td> </tr> {% endfor %} </tbody> </table> </div> {% endblock mainframe %} I have read the following thread but can’t really make sense of it. Django check if checkbox is selected All I want to do is for each row that have the checkbox enabled (checked): Send a query to DB to update that same row where I will set field “setting_enab” to “True” Update “setting_descr” for …