Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Channel cant import ChannelTestCase
Its weird but I am unable to import these statements: from channels import Group from channels import Channel from channels.test import ChannelTestCase However, I am able to import: from channels.generic.websocket import WebsocketConsumer Does anyone know why? -
Django Nested Serializers Attribute Error
I am currently using the django rest framework to develop a website. I have nested my serializers and overwrote the create method in my serializer. I am also using generic views for convenience. I am continually getting this error: AttributeError: Got AttributeError when attempting to get a value for field briefingAgencies on serializer BriefingsSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Briefings instance. My Models: class Briefings(models.Model): briefingsID = models.AutoField(db_column = 'briefingsID', primary_key = True) # Field name made lowercase. Maybe use UUIDField? title = models.CharField(db_column = 'title', max_length = 200, null = True) class Meta: managed = True db_table = 'Briefings' class BriefingAgencies(models.Model): briefingAgenciesID = models.AutoField(db_column = 'briefingAgenciesID', primary_key = True) briefingID = models.ForeignKey(to = 'Briefings', on_delete = models.PROTECT, null = True) agencyID = models.ForeignKey(to = 'Companies', on_delete = models.PROTECT, db_column = 'agencyID', null = True) status = models.IntegerField(db_column = 'status') class Meta: managed = True db_table = 'BriefingAgencies' unique_together = (("briefingID", "agencyID"),) Serializers class BriefingAgenciesSerializer(serializers.ModelSerializer): class Meta: model = BriefingAgencies fields = ('agencyID', 'status') class BriefingsSerializer(serializers.ModelSerializer): briefingAgencies = BriefingAgenciesSerializer(many = True) class Meta: model = Briefings fields = ('title' , 'briefingAgencies', ) def create(self, validated_data): briefingAgencies = validated_data.pop('briefingAgencies') briefings … -
ssh tunnel and Protocol mismatch
I would like to make local port forwarding, to have remote resources accessible on my local machine. I run: ssh -L local_port:remote_address:remote_port username@server.com I run command in django on my local machine and nothing. More, I run website under 127.0.0.1:8888 and I recived: Protocol mismatch. -
Python HTTPConnectionPOOL Error (Python 2.7)
Got the error when trying to execute the following: requests.post('http://xx.xx.xx.xx/url/',data='[{"ModuleCode": "ProductTimeline"}, {"user_id": "90"}]',headers={'Content-type': 'application/json'}) The port and domain both are open Requests Version: requests (2.11.1) Python Version : 2.7.10 Error : HTTPConnectionPool(host='IP', port=80): Max retries exceeded with url: /xxx/xx/ (Caused by NewConnectionError(': Failed to establish a new connection: [Errno 110] Connection timed out',)) object of type 'NoneType' has no len() None Internal Server Error: /xyz/xxxx Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python2.7/site-packages/rest_framework/views.py", line 491, in dispatch self.response = self.finalize_response(request, response, *args, **kwargs) File "/usr/local/lib/python2.7/site-packages/rest_framework/views.py", line 406, in finalize_response % type(response) AssertionError: Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <type 'NoneType'> -
django post_signal triggered on form.save(commit=False)
I have a base User model and two other models Candidate and Company User: email password is_company => default=False In my user creation form: if form.is_valid(): user = form.save(commit=False) user.is_active = False user.is_company = True user.save() I have created a post_save signal for the above model. @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: if instance.is_company: Company.objects.create(user=instance) instance.company.save() else: Candidate.objects.create(user=instance, first_name=instance.is_institute ) instance.candidate.save() The problem is the form.save(commit=False) is triggering the post_save signal. I end up having instance.is_company as False, thus creating a CandidateProfile for a Company. Please help! -
How can I setup my Djano server on LAN
I have made a Django employee portal which will be accessed by LAN only. It works when another employee opens it by typing the IP address of the server on their web browser. However I don't have much experience with Django and I think that this is not the proper way to do so. I run my server using python manage.py runserver and use sqlite3 as database. Is this the correct way to do so? How should I deploy my portal. I am very new to Django and would appreciate some help. I am using a windows machine and I used pycharm to make my project. -
jQuery: Set value into form input fields
I want to set value into input fields such as text input, select input. The form input that I want to insert value is created using Django forms. What is wrong with the code, why couldn't I set the values into input fields? Does setting value in text and select field differ from one another? jQuery //Edit OnClick- Question $(".table-row td:not(:has(input))").on("click", (function(){ $('#editModal').modal('show'); let rowId = $(this).closest('tr').attr('data-id'); var test_id, question_type, question_name, option; $.ajax({ url: "{% url 'edit_question' %}", type: 'GET', data: {"rowId" : rowId}, dataType: 'json', success: function(data){ test_name = data.question[0]['test_name']; question_name = data.question[0]['question_name']; question_type = data.question[0]['question_type']; option = parseInt(data.question[1].length); console.log(question_name, question_type, test_name) $("#question_name").val(question_name); $("#question_type").val(question_type); $("#test_id").val(test_name); }, }); })); The console print question_name, question_type and test_name. It works fine. But I couldn't set the value into the input field. forms.py class QuestionForm(ModelForm): class Meta: model = Question fields = ['test_id','question_type','question_name'] test_id = forms.ModelChoiceField(queryset=Test.objects.all(), empty_label=None, label='Test', widget=forms.Select( attrs={ 'id': "test_id", 'name': "test_id", 'title': 'Select a Test', 'class': 'selectpicker form-control', 'data-style': 'btn btn-primary btn-sm', 'data-size': '7', } ) ) question_type = forms.ChoiceField(choices = QUESTION_TYPE, initial='QCM', widget=forms.Select( attrs={ 'id': "question_type", 'name': "question_type", 'title': 'Select a Test', 'class': 'selectpicker form-control', 'data-style': 'btn btn-primary btn-sm', 'data-size': '7', } ) ) question_name = forms.CharField(label='Question', widget=forms.TextInput( attrs={ … -
Using two versions of jQuery, and libraries using previous version of jQuery
I am trying to use two versions of jQuery. I've looked up lots of materials, but I couldn't find the information that I specifically want. This link shows how to use two versions of jQuery, but doesn't really prepare for a case in which there are other libraries that uses specific version of jQuery. HTML File <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <!-- Meta, title, CSS, favicons, etc. --> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> {% load staticfiles %} <!-- Bootstrap 3.3.7 --> <link type="text/css" rel="stylesheet" href="{% static "/bootstrap-3.3.7/dist/css/bootstrap.min.css" %}"> <!-- Bootstrap 4.1.1 --> <link type="text/css" rel="stylesheet" href="{% static "/bootstrap-4.1.1/dist/css/bootstrap.min.css" %}"> <!-- Font Awesome --> <link type="text/css" rel="stylesheet" href="{% static "/font-awesome/css/font-awesome.min.css" %}"> <!-- NProgress --> <link type="text/css" rel="stylesheet" href="{% static "/nprogress/nprogress.css" %}"> <!-- iCheck --> <link type="text/css" rel="stylesheet" href="{% static "/iCheck/skins/flat/green.css" %}"> <!-- bootstrap-daterangepicker --> <link type="text/css" rel="stylesheet" href="{% static "/bootstrap-daterangepicker/daterangepicker.css" %}"> <!-- bootstrap-datetimepicker --> <link type="text/css" rel="stylesheet" href="{% static "/bootstrap-datetimepicker/build/css/bootstrap-datetimepicker.css" %}"> <!-- Google Code Prettify --> <link type="text/css" rel="stylesheet" href="{% static "/google-code-prettify/bin/prettify.min.css" %}"> <!-- Select2 --> <link type="text/css" rel="stylesheet" href="{% static "/select2/dist/css/select2.min.css" %}"> <!-- Switchery --> <link type="text/css" rel="stylesheet" href="{% static "/switchery/dist/switchery.min.css" %}"> <!-- starrr --> <link type="text/css" rel="stylesheet" href="{% static "/starrr/dist/starrr.css" %}"> … -
Django choicefield change affect charfield value
I am new with Django and I am trying to change dynamically the value of a charfield according to the change of the choicefield. For example if the choicefield is displaying "A", I want that the charfield containts the value "Anaconda", and if I change the choicefield to the "B" value, I want the charfield to show "Boa". Is there any way to do this with Django ? Thank you. -
Django; How to improve too expensive query without filter?
I try to filter objects using a python type method. The query works as intended but is very expensive. Can you see a way to do better in terms of performance? I guess I can not use a filter here. all_badges = Badge.objects.select_related('user') pks_badges_linked_to_convive = [badge.pk for badge in all_badges if type(badge.user.profile) == Convive] return self.filter(pk__in=pks_badges_linked_to_convive) -
ModelChoicesField returns Non-Valid-Choice error, although form is valid
If have a date picker form that filters a set of models (Sonde) and populates a ModelChoicesField. This works correctly in terms of date choice in my app, but on my canvas I constantly get the error: Select a valid choice. That choice is not one of the available choices. I do the init, to filter the available instances of Sonde and populate the choices of the ModelChoicesField. From my forms.py class date_choice(forms.Form): avSonden = forms.ModelChoiceField(queryset = Sonde.objects.none()) def __init__(self, *args, **kwargs): currentUserID = kwargs.pop('currentUserID', None) super(date_choice, self).__init__(*args, **kwargs) if currentUserID: self.fields['avSonden'].queryset = Sonde.objects.filter(owned_by__Kundennummer = currentUserID).values_list("Serial",flat=True).distinct() start = forms.DateField(input_formats=['%Y-%m-%d']) end = forms.DateField(input_formats=['%Y-%m-%d']) -
Django_tables2 using checkbox
I used “django_tables2” for my web page. Now I am trying to add the checkbox for every row, but sounds like it is working column by column. Could you please help to add checkboxes for my rows. I have table I want to add the checkbox in table -
csrf_token missing and how to get details for specific id entered by user
I am trying to display the result for the specific id entered by the user. I 'm not sure about the view.py file also. What changes should I need to make to get the desired result? view.py file def show(request): if request.method == 'POST': Num = allData.objects.only('emp_no') data = request.POST.get('emp_no') if data.is_valid(): for n in Num: if n == data: empid = data emp = {'emp_no':data} return render(request,'system/show.html',{'emp_no':data}) return(data.errors) return HttpResponse("<h2>OOPS!! NO RECORD FOUND</h2>") show.html {% extends 'system/base.html' %} {% load staticfiles %} {% block body_block %} <div class="container" "jumbotron"> <h2>Details</h2> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <label class="lb" for="emp_no" >Employee No.</label> <input type="number" name="emp_no"> <button type="submit" class="btn btn-success">SUBMIT</button> </form> {% for allData in emp_no %} {{ allData.GENDER_CHOICE}} {{ allData.first_name }} {{ allData.last_name }} {{ allData.birth_day }} {{ allData.hire_date }} {{ allData.dept_no }} {{ allData.dept_name }} {{ allData.salary }} {{ allData.from_date }} {{ allData.to_date }} {{ allData.titles }} {% endfor %} </div> {% endblock %} -
How to use 'order_by' with including non-ASCII characters in django?
I use python3 and sqlite on my database. I try to order words on spesific languages. For example I wrote on my settings.py this code part: export LANG='tr_TR.UTF-8' export LC_ALL='tr_TR.UTF-8' However, this code part give syntax error. Eventhough I fix that syntax error, I assume that the problem will still continue. Then I try to change this code part on settings.py: LANGUAGE_CODE = 'tr-TR' But it didn't work either. I guess I have to change something on manage.py, but I don't know what should I change or add. I hope that someone will help on my problem. -
Fix your URL conf, or set the `.lookup_field` attribute on the view correctly
I am trying to post from my html page and getting following error. However it works fine from PostMan.I have implemented it using generics.GenerivAPIView.But getting error which says AssertionError: Expected view OrganisationListView to be called with a URL keyword argument named "id". Fix your URL conf, or set the .lookup_field attribute on the view correctly. [10/Jul/2018 08:30:09] "OPTIONS /api/client/Organisation/ HTTP/1.1" 500 14720 class OrganisationListView(generics.GenericAPIView, mixins.ListModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.RetrieveModelMixin, mixins.DestroyModelMixin): serializer_class = OrganisationSerilizer Organisation.objects.get(id=self.request.Organisation.id) queryset = Organisation.objects.all() # allowed_methods = ('GET', 'POST', 'PUT', 'HEAD', 'DELETE') filter_backends = (DjangoFilterBackend,OrderingFilter, SearchFilter) filter_class = OrganisationFilter ordering_fields = ('name','active') search_fields = ('name',) # for key lookup_field = 'id' def get(self, request, id=None): if id: print("get called with") return self.retrieve(request, id) else: print("get called without ID") return self.list(request) def post(self, request, *args, **kwargs): # queryset = self.filter_queryset(self.get_queryset()) print(request.data) print("Hello") return self.create(request, *args, **kwargs) def perform_create(self, serializer): serializer.save() def put(self, request, id=None): return self.update(request, id) def delete(self,request,id=None): print(request.data) print(id) return self.destroy(request,id) -
Django. How to store parent model fields from mixin in child model?
please I have an issue with model relationships in my Django project. For instance I have a model Foo which inherits from a model mixin FooBarMixin which is an abstract class and Bar which is a model but has a OnetoOne relationship with Foo. Basically this is the current implementation. class Foo(FooBarMixin): pass class FooBarMixin(model.Model): bar = model.OneToOneField(Bar, on_delete=CASCADE, related_name="tracked_%(class)s") class Meta: abstract = True class Bar(model.Model): pass Is it possible to store Bar data on the child model Foo without using a OnetoOne relationship ? and if so how do I go about it? Thank you -
Django Application for building dynamic Tables (Like Excel)
for a project i want to transfer my Excel-Tool to a django-based website. I want to create a dynamic table. At best, you can choose with a drop-down-menu properties (which will be in the columns) for your object (which will be in the first column of the row). At the end of the row, the object gets a title based on the apellations added in the particular columns. Here you can the see how my excel-tool looks like. Is there a possibility to transfer this kind of table into django? I tried django-tables2, but this doesn't seem to offer the specifiy functions i needed. If there isn't such application, do you guys know another framework to work with? I'm a newbie to programming, so please be patient with me :) -
Django wrong request.POST attribute value saved
I am experiencing the issue that the code saves request.POST['name'] value to assumptions.Name field in database, but only the last value in the list which is 'B' in this case. How could I make it save both prefixes 'A' and 'B' to database field Name based on respective forms. When I debug I see both 'A' and 'B' with key 'name'. Please kindly advise how to solve it. Thank you. views.py from django.shortcuts import render from .forms import modelformset_factory, AssumptionsForm from .models import Assumptions from django.core.exceptions import ValidationError model_names = ['A', 'B'] def get_assumptions(request): AssumptionFormset = modelformset_factory( Assumptions, form=AssumptionsForm, extra=5) if request.method == 'POST': formsets = [AssumptionFormset(request.POST, prefix=thing) for thing in model_names] if all([formset.is_valid() for formset in formsets]): for formset in formsets: for form in formset: assumption_data = form.save(commit=False) assumption_data.Name = request.POST.get('name') assumption_data.save() else: formsets = [AssumptionFormset(prefix=thing) for thing in model_names] return render(request, 'assumptions.html', {'formsets': formsets}) assumptions.html <div class="form"> <form action="" method="post"> {% for formset in formsets %} {% csrf_token %} {{ formset.management_form }} {{ formset.non_form_errors.as_ul }} <h1>{{formset.prefix}}</h1> <table id="formset" class="form"> {% for form in formset.forms %} {% if forloop.first %} <thead><tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr></thead> {% endif %} <tr class="{% … -
Combining data from two tables in one view in Django
I have done a lot of searches and found some amazing answers on this topic for the last couple of days while I try to figure this out. But none of those worked for me, as it seems the situation is different than the earlier posted answers, or not working with my version of Django. So here goes: I need to get data from 3 tables and displayed certain columns on a webinterface. I have no problem getting one table, but the other two (linked by foreign keys) I can't seem to get into the view. The code I have is as follows (mind you, I am learning python and django): models.py: class students(models.Model): date_created = models.DateTimeField() project = models.ForeignKey('projects',models.SET_NULL,blank=True,null=True,) name = models.TextField() return_date = models.TextField() class sysinfo(models.Model): student = models.ForeignKey('students',models.SET_NULL,blank=True,null=True,) latest_info = models.DateTimeField() machine = models.TextField(blank=True, null=True) version = models.TextField(blank=True, null=True) platform = models.TextField(blank=True, null=True) hostname = models.TextField(blank=True, null=True) class projects(models.Model): project_name = models.TextField() date_created = models.DateTimeField() date_closed = models.DateTimeField(blank=True, null=True) views.py from django.shortcuts import render from front.models import students, projects, sysinfo # Create your views here. def index(request): list_students = students.objects.select_related('projects','sysinfo').order_by('-last_seen') return render(request, 'main/home.html',{'students': list_students}) This shows the student id and the date created and return date on … -
Firefox does not save file with extension
I have a view in my Django application which creates a XLSX file and returns it to the user for download: # Creates the response response = HttpResponse(output.read(), content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") response['Content-Disposition'] = 'attachment; filename="{}".xlsx'.format(tournament.name) When I try to download the file in Chrome, it works perfectly: the file is downloaded with filename "blabla.xlsx". However with Firefox, it is downloaded with filename "blabla" (no extension). Did you ever encounter this problem? -
How to set Django form initial value only one field?
forms.py class ExForm(forms.Form): a = forms.CharField(max_length=100) b = forms.ChoiceField(choices=SOME_CHOICES) c = forms.ChoiceField(choices=SOME_CHOICES) def __init__(self, request, *args, **kwargs): super(ExForm, self).__init__(*args, **kwargs) self.initial['a'] = 'something value' views.py def view(request): form = ExForm(request.GET or None) return render(request, 'a.html', {'form': form}) I want to set an initial value to 'a' field only. When I submit this form, b and c fields values not set in the form from request.GET. It works. def __init__(self, request, *args, **kwargs): super(ExForm, self).__init__(*args, **kwargs) self.initial['a'] = 'something value' self.initial['b'] = request.b self.initial['c'] = request.c I want to know how to set initial value only one field. Do I set all field initial values? -
Why do we extend HTTPResponse in Django?
I am looking at django-jquery-file-upload This is response file MIMEANY = '*/*' MIMEJSON = 'application/json' MIMETEXT = 'text/plain' def response_mimetype(request): """response_mimetype -- Return a proper response mimetype, accordingly to what the client accepts, as available in the `HTTP_ACCEPT` header. request -- a HttpRequest instance. """ can_json = MIMEJSON in request.META['HTTP_ACCEPT'] can_json |= MIMEANY in request.META['HTTP_ACCEPT'] return MIMEJSON if can_json else MIMETEXT class JSONResponse(HttpResponse): """JSONResponse -- Extends HTTPResponse to handle JSON format response. This response can be used in any view that should return a json stream of data. Usage: def a_iew(request): content = {'key': 'value'} return JSONResponse(content, mimetype=response_mimetype(request)) """ def __init__(self, obj='', json_opts=None, mimetype=MIMEJSON, *args, **kwargs): json_opts = json_opts if isinstance(json_opts, dict) else {} content = json.dumps(obj, **json_opts) super(JSONResponse, self).__init__(content, mimetype, *args, **kwargs) I do not understand how form_valid(views) is constructed. def form_valid(self, form): self.object = form.save() files = [serialize(self.object)] data = {'files': files} response = JSONResponse(data, mimetype=response_mimetype(self.request)) response['Content-Disposition'] = 'inline; filename=files.json' return response What is the benefit of using JSON response over HTTPResponse? -
django-auth-ldap members groups not woking
i managed to get ldap authentification working, but the users groups aren't. when a user is autheticated the username, firstname, email ..etc are copied to the session, but the boolean values (gotten from the groups the user belongs to) aren't. this is my settings.py : AUTHENTICATION_BACKENDS = [ 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ] import ldap from django_auth_ldap.config import LDAPSearch, GroupOfNamesType, GroupOfUniqueNamesType AUTH_LDAP_SERVER_URI = "ldap://openldap" AUTH_LDAP_BIND_DN = "cn=admin,dc=openldap" AUTH_LDAP_BIND_PASSWORD = "admin" AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=django,dc=openldap", ldap.SCOPE_SUBTREE, "(cn=%(user)s)") AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail", } AUTH_LDAP_CACHE_TIMEOUT = 0 AUTH_LDAP_GROUP_CACHE_TIMEOUT = 0 AUTH_LDAP_PROFILE_ATTR_MAP = {"home_directory": "homeDirectory"} AUTH_LDAP_MIRROR_GROUPS = True AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_ALWAYS_UPDATE_USER = True AUTH_LDAP_GROUP_SEARCH = LDAPSearch("dc=openldap", ldap.SCOPE_SUBTREE, "(objectClass=*)" ) AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr='cn') AUTH_LDAP_USER_FLAGS_BY_GROUP = { 'is_active': 'cn=active,ou=groups,dc=openldap', 'is_staff': 'cn=staff,ou=groups,dc=openldap', 'is_superuser': 'cn=superuser,ou=groups,dc=openldap', } # # Simple group restrictions # AUTH_LDAP_REQUIRE_GROUP = 'cn=enabled,ou=groups,dc=openldap', # AUTH_LDAP_DENY_GROUP = 'cn=disabled,ou=groups,dc=openldap', ### ERROR LOGGING import logging logger = logging.getLogger('django_auth_ldap') logger.addHandler(logging.StreamHandler()) logger.setLevel(logging.DEBUG) this is my ldap scheme : root is part of active, staff and superuser. user1 is part of active. this is what i get when i authenticate a user from a view: i get the error -> is not a memeber of openldap | 5b444c1f conn=1015 fd=13 ACCEPT from IP=172.23.0.4:47230 (IP=0.0.0.0:389) openldap | 5b444c1f conn=1015 op=0 … -
How to access foreign key while validating form in django?
In the django project I was working on, there are classes named Course and Assignment. Assignment is related to Course by foreignkey as shown here: class Assignment(models.Model): course = models.ForeignKey(Course, related_name='get_assignments') So every course has few assignments. To create assignments in a course, form named AssignmentForm is used. In the assignment form, while validating it, in a function, I want to get the name of Course in which assignment is created. How should I get that? This is what I've done: def clean_bulk_add(self): assig1 = self.cleaned_data['name'] course1 = self.this_course user1 = course1.owner tot1 = 30 + len(str(user1)) + len(str(course1.title)) + len(str(assig1)) + len(str(self.cleaned_data['bulk_add'])) if tot1 > 7 : raise forms.ValidationError("Assignment or Course name is too long: "+str(tot1)) return self.cleaned_data['bulk_add'] Error I got: -
how to read data from Shield UI grid datasource after applying savechanges method?
I am using Shield UI grid for displaying data in html page.I have applied savechanges method on datasource. I want to pass this saved data to excel. How can i read the updated data from the data source using java script.