Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Displaying label on first form of Django formset only
This is a super straightforward question but I can't seem to find any concise answer it. I have a Django formset that displays different tags associated with an object. Here is the form: class TagForm(forms.Form): def __init__(self, *args, **kwargs): tags = kwargs.pop('tags') super(TagForm, self).__init__(*args, **kwargs) self.fields['tags'] = forms.ChoiceField(choices=[(tag, tag) for tag in tags], label="Tags") I'm rendering the formset using the following code: <li class="list-group-item"> <ul class="list-inline" id="tag-group"> {{ tag_formset.management_form }} {% for tag_form in tag_formset %} <li class="list-inline-item"> {{ tag_form.tags.label_tag }} {{ tag_form.tags }} </li> {% endfor %} </ul> </li> My problem is that this creates a label for each tag. Since this is an inline list, I'd only like to display the label prior to the first tag (and no others). I can't find any straightforward way to do this (without modifying the for loop with explicit logic checking if it is the first form being rendered). I optimistically tried to modify my rendering code to the following: <li class="list-group-item"> <ul class="list-inline" id="tag-group"> {{ tag_formset.management_form }} {{ tag_form.empty_form.label_tag }} {% for tag_form in tag_formset %} <li class="list-inline-item"> {{ tag_form.tags }} </li> {% endfor %} </ul> </li> but this didn't display any labels at all. Is there an idiomatic way … -
Django unrecognized token: "@" while query
I simply want to implement a search view into my Django app. But when i try to search something on my App i get the following error: 'unrecognized token: "@"' In the end i want that my Query is a combination of category and searchword. So that the user can filter specific categories (Just like Amazon.com searchfield) e.g.: http://127.0.0.1:8000/search/?category=1&q=hallo base.html ... <div class="globalsearch"> <form id="searchform" action="{% url 'search' %}" method="get" accept-charset="utf-8"> <label for="{{ categorysearch_form.category.id_for_label }}">In category: </label> {{ categorysearch_form.category }} <input class="searchfield" id="searchbox" name="q" type="text" placeholder="Search for ..."> <button class="searchbutton" type="submit"> <i class="fa fa-search"></i> </button> </form> </div> </div> ... categorysearch_form is a dropdown selector that gets his ID from the Database. views.py ... from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector from django.views.generic import ListView class globalsearch(ListView): """ Display a Post List page filtered by the search query. """ model = Post paginate_by = 10 def get_queryset(self): qs = Post.objects.all() keywords = self.request.GET.get('q') if keywords: query = SearchQuery(keywords) title_vector = SearchVector('title', weight='A') content_vector = SearchVector('content', weight='B') tag_vector = SearchVector('tag', weight='C') vectors = title_vector + content_vector + tag_vector qs = qs.annotate(search=vectors).filter(search=query) qs = qs.annotate(rank=SearchRank(vectors, query)).order_by('-rank') return qs ... urls.py ... url(r'^search/$', views.globalsearch.as_view(), name='search'), ... Search.html results are getting displayd here: {% extends 'quickblog/base.html' … -
FATAL: too many connections for role "tliwvkmzuvklzz"
I have a running Django project and its working very well,, but sometimes it gives me that strange error : FATAL: too many connections for role "tliwvkmzuvklzz" and it works again after some refreshes .. the error appears very randomly, I can never find out where is the exact problem. here is the website: http://www.fostania.com If someone knows about this error and want me to share some more information kindly ask for it. Also, Before mark as dubplicated please note that I've searched almost everyone and didn't find a straight answer -
Creating a new virtualenv project and creating a virtualenv for existing project causes error
I've tried to search for a solution or a thread handling this problem but I have a hard time expressing it in the first place since I'm fairly new to django, virtualenv, pip etc. I'm using windows 10 and I do everything below in powershell. When I started my first project, named fadderjobb, I didn't use virtualenv. I installed a couple of packages using pip install. Now when I started my second project, wingqvist, I installed virtualenv, made a virtual environment in a folder envs/wingqvist, installed Django and created a new Django project in another new folder webdev/wingqvist. Looking something like this. webdev |-- fadderjobb | `-- projectfiles for fadderjobb |-- wingqvist | `-- projectfiles for wingqvist `-- envs `-- wingqvist `-- virualenv files for wingqvist When I in my virtualenv (wingqvist) tried to run python manage.py migrate in webdev/wingqvist/ i got the following error: (wingqvist) PS C:\Users\Viktor Wingqvist\documents\webdev\wingqvist> python manage.py migrate Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\Viktor Wingqvist\documents\webdev\envs\wingqvist\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\Viktor Wingqvist\documents\webdev\envs\wingqvist\lib\site-packages\django\core\management\__init__.py", line 347, in execute django.setup() File "C:\Users\Viktor Wingqvist\documents\webdev\envs\wingqvist\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Viktor Wingqvist\documents\webdev\envs\wingqvist\lib\site-packages\django\apps\registry.py", line 89, in populate app_config = AppConfig.create(entry) File "C:\Users\Viktor … -
bokeh pass 2 plots via layout
I can pass one plot and slider in django but how can I pass second plot, slider. l = layout(children=[row(p1, date_range_slider)], sizing_mode='fixed') script, div = components(l) return render(request, 'index.html', {"the_script": script, "the_div": div}) And index.html contains body {{the_script | safe}} {{the_div | safe}} But how can pass row(p2, date_range_slider) and plot second graph? I see to pass 2 plots to components as components({"Plot 1": plot1, "Plot 2": plot2}) and access in html as e.g. the_div.Plot 1But how do I pass and access through layout -
Django get max field value across filtered group of model instances
I need some help creating a custom Django query in my View. I have two models, Department and Team, each Department can have multiple Teams. A user can manually sort the Teams in any order and once done the order field is updated on each Team instance. So, now when a new Team is created I want to get the largest Team.order value within a specific Department. This part below returns all of the Team instances Team.objects.filter(department=team.department.id), but how do I then get the max value from the order field (other than looping)? VIEW class TeamCreate(LoginRequiredMixin, CreateView): model = Team form_class = TeamForm template_name = 'app/sidebar_team.html' # def get_initial(self): def get_initial(self): pk = self.request.GET.get('id') return { 'department': pk, } def post(self, request, *args, **kwargs): form = TeamForm(request.POST) if form.is_valid(): team = form.save(commit=False) team.author = request.user team.modified_date = timezone.now() # Get max Team.order value, increment by one, and set as new team.order max = Team.objects.filter(department=team.department.id).extra(Max('order')) team.save() return redirect('/dashboard/' + str(team.department.id)) else: return redirect('/dashboard/' + str(form.department.id)) -
Address already in use (Errno 98) django with vscode and docker
I have a python application with django and I'm running it inside a docker container. I need to debug this application and every time I do the docker-compose up it gives this error below. I looked at several sites on how to debug and none of the solutions helped me. Does anyone know what can it be? I think the most important files for you to evaluate are below, if there is need of any more I edit the post. I'm using django 2.0.1, ptvsd 3.2.1 and the Docker-Toolbox. File "manage.py", line 10, in <module> ptvsd.enable_attach(secret='my_secret', address = ('192.168.99.100', 3000)) File "/usr/local/lib/python3.6/site-packages/ptvsd/__init__.py", line 87, in enable_attach return _attach_server().enable_attach(secret, address, certfile, keyfile, redirect_output) File "/usr/local/lib/python3.6/site-packages/ptvsd/attach_server.py", line 109, in enable_attach server.bind(address) OSError: [Errno 99] Cannot assign requested addres s manage.py: #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "chatire.settings") try: from django.core.management import execute_from_command_line import ptvsd ptvsd.enable_attach(secret='my_secret', address = ('192.168.99.100', 3000)) except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) docker-compose.yml: version: '3' services: db: image: postgres backend: build: . command: bash app.sh … -
Other than DB setup and connection, Is there any other differences while using MySQL instead of SQLite3 in Django?
Pardon me if I have structured the question wrongly. I am new to Django and I started learning it yesterday. 😅 By difference I mean, like the DB queries. For example for a login/registration in PHP/MySQL, you need to store them and check the credentials via MySQL queries in PHP right? Similarly is there any MySQL specific codes required here? -
Javascript remove previous error message when formset is created
So I am creating a formset with Django and I do validation with clean_variable_name in my forms.py. My problem is when I add to create another form, it will give me the empty form with error message previous form generated. I would like to have reset error message.. I got JS file from the library,, I don't entirely understand the code. Can you also explain it to me if possible? forms.py def clean_type(self): type = self.cleaned_data['type'] if type not in {'A', 'B', 'C', 'D', 'a', 'b', 'c', 'd'}: raise forms.ValidationError("Please enter from A to D") return type HTML <div class="row"> <div class="col-25"> <label for="type">TYPE:</label> </div> <div class="col-75"> <span class="text-danger" small>{{ form.type.errors }}</span> {{ form.type }} </div> </div> JavaScript <script> function updateElementIndex(el, prefix, ndx) { var id_regex = new RegExp('(' + prefix + '-\\d+)'); var replacement = prefix + '-' + ndx; if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex, replacement)); if (el.id) el.id = el.id.replace(id_regex, replacement); if (el.name) el.name = el.name.replace(id_regex, replacement); } function cloneMore(selector, prefix) { var newElement = $(selector).clone(true); var total = $('#id_' + prefix + '-TOTAL_FORMS').val(); newElement.find(':input').each(function () { if (this.type == "submit") return; var name = $(this).attr('name').replace('-' + (total - 1) + '-', '-' + total + '-'); var id … -
Django: 'Manager' object has no attribute 'published'
I simply want to implement a search view into my Django app. But when i try to search something on my App i get the following error: 'Manager' object has no attribute 'published' In the end i want that my Query is a combination of category and searchword. So that the user can filter specific categories (Just like Amazon.com searchfield) e.g.: http://127.0.0.1:8000/search/?category=1&q=hallo base.html ... <div class="globalsearch"> <form id="searchform" action="{% url 'search' %}" method="get" accept-charset="utf-8"> <label for="{{ categorysearch_form.category.id_for_label }}">In category: </label> {{ categorysearch_form.category }} <input class="searchfield" id="searchbox" name="q" type="text" placeholder="Search for ..."> <button class="searchbutton" type="submit"> <i class="fa fa-search"></i> </button> </form> </div> </div> ... categorysearch_form is a dropdown selector that gets his ID from the Database. views.py ... from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector from django.views.generic import ListView class globalsearch(ListView): """ Display a Post List page filtered by the search query. """ model = Post paginate_by = 10 def get_queryset(self): qs = Post.objects.published() keywords = self.request.GET.get('q') if keywords: query = SearchQuery(keywords) title_vector = SearchVector('title', weight='A') content_vector = SearchVector('content', weight='B') tag_vector = SearchVector('tag', weight='C') vectors = title_vector + content_vector + tag_vector qs = qs.annotate(search=vectors).filter(search=query) qs = qs.annotate(rank=SearchRank(vectors, query)).order_by('-rank') return qs ... urls.py ... url(r'^search/$', views.globalsearch.as_view(), name='search'), ... Search.html results are getting displayd here: … -
TypeError: quote_from_bytes() expected bytes
I'm following this tutorial. When I run test_views.py I have an error that shouldn't be there according the author: TypeError: quote_from_bytes() expected bytes. My views and my test_views are the same like the book, but I'm using django 2.0.6 instead django 1.11 so my url.py change, so maybe here's the problem. My lists/urls.py: urlpatterns = [ path('new', views.new_list, name='new_list'), path('<slug:list_id>/', views.view_list, name='view_list'), path('users/<email>/', # I'm not sure about this one but it works in other tests views.my_lists, name='my_lists'), ] #instead of: #urlpatterns = [ # url(r'^new$', views.new_list, name='new_list'), # url(r'^(\d+)/$', views.view_list, name='view_list'), # url(r'^users/(.+)/$', views.my_lists, name='my_lists'), #] My lists/views.py: [...] def new_list(request): form = ItemForm(data=request.POST) if form.is_valid(): list_ = List() list_.owner = request.user list_.save() form.save(for_list=list_) return redirect(list_) else: return render(request, 'home.html', {"form": form}) My lists/tests/test_views.py: @patch('lists.views.List') @patch('lists.views.ItemForm') def test_list_owner_is_saved_if_user_is_authenticated(self, mockItemFormClass, mockListClass ): user = User.objects.create(email='a@b.com') self.client.force_login(user) self.client.post('/lists/new', data={'text': 'new item'}) mock_list = mockListClass.return_value self.assertEqual(mock_list.owner, user) My full traceback: What can be? thank you -
Django: filtering by value or returning all records
I have the following piece of code (django, python): def function(self, some_id): if some_id: return Model1.objects.filter(model2__id=some_id) else: return Model1.objects.all() I'm wondering it is possible to refactoring this code with a single return statement? Model1 has a foreign key on Model2.id. -
Single Input for Multiple Model Formset Instances
I'm trying to figure out how I would go about creating a form that has a single multiplechoicefield with Author's name, exactly 9 empty text fields for Book names, and a single save button. The goal being to select the author once, and add 9 book names to the database. This is relatively straight forward if I use 9 author dropdowns with 9 Book text fields. But how would I go about using a single Author dropdown to populate 9 Book instances? class Author(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Book(models.Model): name = models.CharField(max_length=100) authors = models.ManyToManyField(Author) class BookForm(ModelForm): class Meta: model = Book fields = ['name', 'authors'] def add_two_books(request): BookFormSet = modelformset_factory(Book, form=BookForm, extra=9) formset = BookFormSet(request.POST or None, queryset=Author.objects.none()) -
Periscope plus Django ORM?
I'm working on a Django project that uses Periscope for data visualization. This is all fine and dandy for simple queries but when we get into some of the logic in our ORM, it can get pretty convoluted and brittle to simply hard code a sql query to get what we need visualized. Is there a better way, or at least an automated way to maybe get a succinct QuerySet.query for this purpose? What would be ideal is a way to plug periscope to a higher level like the Model Views. How do you guys solve this problem? -Dash -
Get the next time of starting a Celery periodic task
I have several Celery periodic tasks which were defined via Django Celery admin page. How can I get information using Python about when tasks will be executed in the next time? -
How to fetch data from dropdown selection and display it on the same HTML page? Django
I am doing a project management tool web application. I would like user can choose 'user' from dropdown selection, click 'Add member', then the member will show somewhere under the member?. Here is what I am doing. Please do not worry about the styling. I have not done UI yet. view.py def member_select(request): if request.method == 'GET': selection = request.GET.get('id',None) if selection: selected_member = User.objects.filter(pk=selection) return selected_member project_index.html <form action="" method="GET" id="selection-form"> {% csrf_token %} <select id="member_list"> {% for user in user %} <option> {{ user.username }} </option> {% endfor %} </select> <input type="button" value="Add member" id="selection-button"> </form> base.html <script> var url = $( '#selection-form' ).attr( 'action' ); $("selection-button").onclick(function (e) { e.preventDefault(); $.ajax({ type:'GET', url:url, data:{ id:$('#member_list').val() }, success:function (result) { alert('okay'); }, error:function (result) { alert('error'); } }); }); </script> -
Django Social Auth: Google OAuth2 - only display emails from restricted domain list
I have Django Social Auth (pypi package social-auth-app-django) working with Google OAuth2 on a site. When they open a page they get redirected to Google's OAuth2 authentication. This works great, and if they try to log in with an email address that is not in my restricted list they get an AuthForbidden exception. I've added a catch for this and show them a page that they are not allowed to log into this site. All well and good so far. However, I would prefer to not have the invalid email accounts show up at all in the list from Google's authentication page in the first place. I've done this with manual calls to the authentication page before using javascript with a parameter, but I'm not sure how to do so using the canned Django social auth module. Can this be done and if so, how? I have middleware that detects if a user is not logged in and returns a login() view which redirects them to the Google authentication page. views.py # Login using OAuth2. @csrf_protect def login(request): next_page = request.path if next_page is None or next_page == '': next_page = request.POST.get('next', request.GET.get('next', '')) # Check if they are already … -
How can I resolve query object error - ValueError: Cannot query "mayur": Must be "User" instance
I am trying to access my followers in the available module, I can get the number of count such as the number of followers and number of followings but I can't get the list of followers to see my followers. Need suggestions. My module.py File: from django.db import models class FollowerFollowing(models.Model): user_from = models.ForeignKey('User', on_delete=models.SET_NULL, null=True, related_name='rel_from_set') user_to = models.ForeignKey('User', on_delete=models.SET_NULL, null=True, related_name='rel_to_set') created = models.DateTimeField(auto_now_add=True, db_index=True) class Meta: ordering = ('-created',) def __str__(self): return '{} follows {}'.format(self.user_from, self.user_to) User.add_to_class('following', models.ManyToManyField('User', through=FollowerFollowing, related_name='followers', symmetrical=False)) My views.py File: def follower(request): print(request) if request.session['user_id']: query = FollowerFollowing.objects.filter(user_from=request.user) print(query) context = { 'query': query } return render(request, 'Instagram_app/following.html', context) else: pass return HttpResponse("No user logged in") follower.html (template) {% extends 'Instagram_app/home.html'%} {% block content %} <h2>following</h2> <div id="action-list"> {% for result in query %} <h1>{{ result }}</h1> {% endfor %} </div> {% endblock %} Console error is: (value, opts.object_name)) ValueError: Cannot query "mayur": Must be "User" instance. [20/Jun/2018 11:45:27] "GET /Instagram_app/follower HTTP/1.1" 500 105165 Need suggestions to solve this problem. Thank you -
Integrating existing HTML/CSS/JS with Django project
I'm working on a personal project that involves full-stack development of a Social Networking website. I've build a back-end in Django2.0.5 which supports operations like creating a user, posting content, following other users, etc. While developing this, I tested it by printing information in very minimal HTML pages with no CSS or anything, just data that I can read. Now I'm at a point where I want to start building the front-end. I bought an HTML project from ThemeForest to get started, but now I am completely lost on how to actually integrate the two. The theme is in a GULP project configured to watch for changes, sync with the browser, and recompile the Handlebars templates. So far I've looked into: Converting the Handlebars templates into Django templates, and building the front end in Django. It seems like this method would work, and this is how I started out initially. But, it would take about 10 minutes to convert each of the 100+ pages to a usable Django format before even removing the Lorem Ipsum content Create a new Angular project, add the GULP project into it, and have it communicate with the back-end via REST api This seems like … -
Getting error in Vmware "pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available."
I am struggling in installing Django using pip on Vmware. I have tried almost every option available. Command: [root@ora12c src]# pip3.6 install django Output: [root@ora12c src]# pip3.6 install django pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available. Collecting django Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/django/ Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/django/ Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/django/ Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/django/ Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/django/ Could not fetch URL https://pypi.python.org/simple/django/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.python.org', port=443): Max retries exceeded with url: /simple/django/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)) - skipping … -
Trying to JSON.parse serialized data from Django
I want to do some stuff on the client using Javascript. I serialize a Queryset from my models in JSON in my view and send it to the template. data = serializers.serialize("json", Profile.objects.filter(user_id=self.request.user)) I end up with this: var data = '[ { "model": "accounts.profile", "pk": 14, "fields": { "user": 14, "email_confirmed": true, "encrypted_private_key": "Z0FBQUFBQmJLQT09", "public_key": "LS0tLSS0tLQo=", "salt": "I8rzovcWsKm4G5Pj3E4DMw==" } } ]'; When I try to do: var data = JSON.parse('{{ data|safe }}'); I get an error Uncaught SyntaxError: Unexpected token { in JSON at position 1 Can anyone help? -
How to retroactively save an extended Django model?
I'm trying to extend a Django model using inheritance. I have a custom model like: from request.models import Request class RequestExtended(Request): start_time = DateTimeField(_('start time'), default=None, db_index=True, blank=True, null=True, editable=False) total_seconds = FloatField(_('total seconds'), default=None, db_index=True, blank=True, null=True, editable=False) def save(self, *args, **kwargs): start_time = get_current_request_start() total_seconds = None if start_time and self.time: total_seconds = (self.time - start_time).total_seconds() self.start_time = start_time self.total_seconds = total_seconds super(RequestExtended, self).save(*args, **kwargs) There's middleware in the request app that automatically saves a new request record for every Django request processed, but this doesn't automatically trigger creation of my extended model. So I tried adding a post_save signal like: def post_request_save(sender, instance, **kwargs): print('request.id:', instance.id, instance.ip) RequestExtended.objects.get_or_create(request_ptr=instance) post_save.connect(post_request_save, sender=Request) However, this throws an error because RequestExtended is ignoring my request_ptr value and trying to instantiate a blank Request instance and not filling in any required fields. How do you create a model extended through inheritance and link it to an existing record that it's supposed to extend? -
Django Crispy forms Submit does not work with TabHolder, but does work with field sets
For some reason the Submit works fine with Fieldsets, but not with the Tabholder in Django Crispy forms. The tabs work fine, the conditional hiding of fields also works great. Just don't seem to be able to save any changes to the database. Any thoughts? Hereby my code as I use for testing functionalities to improve my Django skills. Models.py class TestCondition(models.Model): some_name = models.ForeignKey(key_name, on_delete=models.CASCADE) A_type_choices = ( ('1','1'), ('2','2'), ) Field_A = models.CharField(max_length=20,choices= A_type_choices,default='1') B_field_choices = ( ('abc','ABC'), ('cba','CBA'), ) Field_B = models.CharField(max_length=20,choices= B_field_choices,default='abc',blank=True,) Field_C = models.CharField(max_length=40, blank=True, default='') Field_D = models.CharField(max_length=40, blank=True, default='') Field_E = models.CharField(max_length=40, blank=True, default='') Forms.py class TestConditionTabForm(ModelForm): class Meta: model = TestCondition fields = ('some_name','Field_A','Field_B','Field_C','Field_D','Field_E',) def __init__(self, *args, **kwargs): super(TestConditionTabForm, self).__init__(*args, **kwargs) self.helper = FormHelper(form=self) self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-lg-2' self.helper.field_class = 'col-lg-8' self.helper.form_method = 'post' self.helper.layout = Layout( TabHolder( Tab( 'Tab1', Field('some_name', type='hidden'), 'Field_A','Field_B','Field_C', ), Tab( 'Tab2', 'Field_D', ), Tab( 'Tab3', 'Field_E', )), Fieldset( 'Test Fieldset submit', Field('some_name', type='hidden'), 'Field_A','Field_B','Field_C','Field_D','Field_E', ), ) self.helper.add_input(Submit('save', 'Submit')) Views.py class ViewUpdateTestForm(LoginRequiredMixin,UpdateView): model = TestCondition template_name = 'test/update.html' form_class = TestConditionTabForm def form_valid(self, form): model = form.save(commit=False) model.save() return HttpResponseRedirect(reverse('test:testds-overview', args=[model.some_name.id])) Update.html {% extends 'base.html' %} {% load static %} {% block content %} <script type="text/javascript" … -
How to get the last date from similar records? | Django
I have next model. Also below you can see table with data. As you can for example A has 2 close records. The difference only in change_date column. I need to take only last date. How to make that with Django ORM? models.py: class Securities(models.Model): name= models.CharField() bool_value = models.BooleanField() code = models.CharField() change_date = models.DateField() bool_value = models.BooleanField() Lets say I have such Table: NAME | CODE | CHANGE_DATE | BOOL_VALUE A | 8328 | 15.02.2018 | 1 A | 8328 | 02.09.2018 | 0 B | 8328 | 02.09.2018 | 1 C | 8328 | 02.09.2018 | 1 C | 8328 | 20.09.2018 | 0 I want to filter next result: NAME | CODE | CHANGE_DATE | BOOL_VALUE A | 8328 | 02.09.2018 | 0 B | 8328 | 02.09.2018 | 1 C | 8328 | 20.09.2018 | 0 -
Issue with pyldap and microsoft ldap
The issue is I have to connect a django develop with microsoft ldap, to create, modify, and authenticate users. In the create exercise I have the next trouble, if I pass the attributes like this: attrs = [ ('objectclass', [b'user', b'top', b'person', b'organizationalPerson']), ('userPassword', [pwd.encode()]), ('displayName', [fullname.encode()]), ('name', fullname.encode()), ('givenName', [names_list[0].encode()]), ('sn', [lastnames_list[0].encode()]),', cn), ('userPrincipalName', userprincipalname),', samaccountname) ] There's no problem and the user is created succesfully but disabled. But, if I pass the parameters like this: attrs = [ ('objectclass', [b'user', b'top', b'person', b'organizationalPerson']), ('userPassword', [pwd.encode()]), ('displayName', [fullname.encode()]), ('name', fullname.encode()), ('givenName', [names_list[0].encode()]), ('sn', [lastnames_list[0].encode()]),', cn), ('userAccountControl', b'512'), ('userPrincipalName', userprincipalname),', samaccountname) ] I get this error on the log: {'info': '0000052D: SvcErr: DSID-031A12D2, problem 5003 (WILL_NOT_PERFORM), data 0\n', 'desc': 'Server is unwilling to perform'} I try with this line too: ('userAccountControl', str(NORMAL_ACCOUNT + DONT_EXPIRE_PASSWORD).encode()), And I get the same error. I try with ldapadd on linux console too and I get the same error. Thanks in advance.