Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to target a Django form with jQuery
I'd like to target my django form with jQuery, but differently of a html select tag, I don't have a class to do that. Could someone help me? Ps: I'm a beginner on programming. <!-- Selection Box --> <div> <form action="" method="post">{% csrf_token %} {{selectfield}} <!-- my form --> <button type="submit">Save</button> </form> </div> <!-- End of Selection Box --> <!-- Jquery Select2 --> <script type="text/javascript"> $(document).ready(function(){ $('.target').select2({ placeholder: "Select here", maximumSelectionSize: 100}); }) </script> <!-- End of JQuery Select2 --> -
Pin only one post in Django-powered blog
I've managed to pin posts on the index page as I wanted to. Thing is, I would like to be able to pin only one post. What I have done is create two methods, one to pin, and another to unpin, the two being BooleanFields. What I would like to do is to, like in Twitter, when you pin one post, the other one before it loses its pinned status, and the just-pinned one takes its place. For now I can manage to pin several things at once. -
Django: Top navigation bar refreshes (flickers) when clicking on menu items
I have developed a Django app with a fixed top navbar, but it sometimes flickers / refreshes when clicking the menu items. Have I made a mistake in extending the templates or it is something else causing this? Here is the app deployed that you can see it: http://azeribocorp.pythonanywhere.com/index/ __base.html: {% load staticfiles %} <!DOCTYPE html> <html lang="en" class="no-js"> <head> {% block meta_tags %}{% endblock meta_tags%} <title> {% block title %}Azeribo Tracking{% endblock title %} </title> {% block stylesheets %} {% endblock stylesheets %} {% block js %} {% endblock js %} </head> <body> <header class="topnavbar" id="TNB" > {% include 'aztracker/_topnavbar.html' %} </header> <div id="main" role="main"> <div class="container"> {% block content %} {% endblock content %} </div> </div> {# /#main #} </body> </html> search_form.html: {% extends 'aztracker/__base.html' %} {% load staticfiles %} {% load static %} {% block stylesheets %} <link rel="stylesheet" type="text/css" href="{% static 'css/__main.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'css/search_form.css' %}"> {% endblock %} {% block content %} {% block main_col %} <section class="search_section"> <form method="POST" action="/search/"> {% csrf_token %} <input required type="search" placeholder="Country or Code" name="search_input_field" id="search_input"> <button id="search_btn" class="flat_button">Search</button> </form> </section> <!-- view all country codes link --> <div class="wrapper"> <a id="list_of_all_countries_link" href="/countries/"> List of … -
Store a Python exception in a Django model
What is the recommended way to store a Python exception – in a structured way that allows access to the different parts of that exception – in a Django model? It is common to design a Django model that records “an event” or “an attempt to do foo”; part of the information to be recorded is “… and the result was this error”. That then becomes a field on the model. An important aspect of recording the error in the database is to query it in various structured ways: What was the exception type? What was the specific message? What were the other arguments to the exception instance? What was the full traceback? So it isn't enough to have a free-form TextField to record a string representation of the exception. A structured field or set of fields is needed; perhaps even an entire separate model for storing exception instances. I'm aware of services that will let me stream logging or errors to them across the network; that is not what this question asks. I need the structured exception data in the project's own database, for reference directly from other models in the same database. Of course I could design such … -
a way to pass m2m field and action into a function's parameter? django
Let's say I have a model which has a m2m field named best. I know by adding things into the best field we can do something like model.best.add(blah) or remove model.best.remove(blah) if I have another m2m field named worst and I want to make a function which will then use the parameter to define if I should be using the best or worst field and if the action is add() or remove Is if possible? I already tried something silly such as: def change(field, action, obj): model.field.action(obj) of course the above will not work, is there a way to make this work so I do not need to do lots IF if I have LOTS m2m fields in one model? Thanks in advance for any advices -
DJango URL error 404
I am trying to get a website using Django to work off of old code and am getting this error when I click on my submit button. The URL file has just been updated how I think it needs to be however it may be wrong. Any help would be greatly appreciated. Page not found (404) Request Method: GET Request URL: http://192.168.2.214/accounts/create?chapter=2 Using the URLconf defined in tsa.urls, Django tried these URL patterns, in this order: ^help/$ [name='help_viewer'] ^help/(\w+)$ [name='help_viewer'] ^contact/$ [name='contact'] ^api/xml$ [name='xml'] ^calendar(?:.ics)?$ [name='calendar'] ^$ [name='index'] ^quick_login$ [name='quick_login'] ^update_indi$ [name='update_indi'] ^settings$ [name='settings'] ^event_list$ [name='event_list'] ^member_list/$ [name='member_list'] ^member_list/(\d+)/$ [name='member_list'] ^team_list/$ [name='team_list'] ^team_list/(\d+)/$ [name='team_list'] ^join_team$ [name='join_team'] ^teams/(\d+)/$ [name='view_team'] ^teams/(\d+)/update/$ [name='update_team'] ^edit_chapter$ [name='edit_chapter'] ^chapter_info$ [name='chapter_info'] ^member_fields/(\w+)?$ [name='member_fields'] ^attendance$ [name='attendance'] ^config/chapter_list$ [name='chapter_list'] ^config/events/(MS|HS)/$ [name='edit_events'] ^config/eventsets/$ [name='eventset_list'] ^config/eventsets/(\d+)/$ [name='edit_eventset'] ^accounts/login/$ [name='tsa.events.views.login_view'] ^accounts/logout/$ [name='tsa.events.views.logout_view'] ^accounts/create/$ [name='tsa.events.views.create_account'] ^accounts/request_chapter/$ [name='tsa.events.views.request_chapter'] ^accounts/reset/$ [name='tsa.events.views.reset_password'] The current path, accounts/create, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. -
executemany() takes exactly 3 arguments (2 given) -- mysql with Python
fields is => [u'sender', u'timestamp', u'number', u'mms', u'datetime', u'text', u'id'] dataList is => [(False, 1475565742761L, u'VM-449100', False, u'2016-10-04 12:52:22 GMT+05:30', u'Some text here', 1276)] cursor = connection.cursor() query = """INSERT INTO messages """+str(tuple(fields))+""" VALUES (%s, %s, %s, %s, %s, %s, %s) """,dataList cursor.executemany(query) On executing the above code i am getting error => executemany() takes exactly 3 arguments (2 given) -
Invalid Object Name - User Model Extension and/or matching query does not exist
My app structure is Security > Accounts I'm getting the following error, but why is it adding accounts_ prior to my table name? Below is the model, i'm still using the User model for my auth_user. [SQL Server]Invalid object name 'accounts_alleeactive'. (208) (SQLExecDirectW)") from __future__ import unicode_literals from django.contrib.auth.models import User from django.db import models from django.forms import ModelForm from django.db.models.signals import post_save from django.dispatch import receiver import django_filters class AllEeActive(models.Model): employee_ntname = models.OneToOneField(User, db_column='Employee_NTName',max_length=12) # Field name made lowercase. employee_last_name = models.CharField(db_column='Employee_Last_Name', max_length=50, blank=True, null=True) # Field name made lowercase. employee_first_name = models.CharField(db_column='Employee_First_Name', max_length=50, blank=True, null=True) # Field name made lowercase. b_level = models.CharField(db_column='B_Level', max_length=10, blank=True, null=True) # Field name made lowercase. group_name = models.CharField(db_column='Group_Name', max_length=100, blank=True, null=True) # Field name made lowercase. r_level = models.CharField(db_column='R_Level', max_length=10, blank=True, null=True) # Field name made lowercase. division_name = models.CharField(db_column='Division_Name', max_length=100, blank=True, null=True) # Field name made lowercase. d_level = models.CharField(db_column='D_Level', max_length=10, blank=True, null=True) # Field name made lowercase. market_name = models.CharField(db_column='Market_Name', max_length=100, blank=True, null=True) # Field name made lowercase. coid = models.CharField(db_column='COID', max_length=50, blank=True, null=True) # Field name made lowercase. unit_no = models.CharField(db_column='Unit_No', max_length=50, blank=True, null=True) # Field name made lowercase. dept_no = models.CharField(db_column='Dept_No', max_length=50, blank=True, null=True) # Field name made … -
How to use Django SelectMultiple to Send Email
I have a simple app that let's someone select a user, write a message, and then sends the message to the user while saving it to the database. I need to add the ability to select multiple users, type a single message, and then send that message to the selected users. It would also need to save that message to each users account. Here is my current code: forms.py from django.forms import ModelForm, Textarea, Select, SelectMultiple from django.contrib.auth.models import User from .models import Update class UpdateForm(ModelForm): class Meta: model = Update fields = ('user', 'update') widgets = { 'user': Select(attrs={'class': 'form-control'}), 'update': Textarea(attrs={'class': 'form-control', 'Placeholder': 'Please enter your update here.'}) } models.py from django.db import models from django.contrib.auth.models import User class Update(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) update = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.update views.py @method_decorator(login_required, name='dispatch') class UpdateFormView(AjaxFormMixin, FormView): template_name = 'update/update_form.html' form_class = UpdateForm success_url = '/' def form_invalid(self, form): response = super(UpdateFormView, self).form_invalid(form) if self.request.is_ajax(): return JsonResponse(form.errors, status=400) else: return response def form_valid(self, form): response = super(UpdateFormView, self).form_valid(form) if self.request.is_ajax(): user = form.cleaned_data['user'] update = form.cleaned_data['update'] update = Update(user=user, update=update) print() update.save() name = user.first_name email = user.email send_complex_message(email, update, name) data … -
dynamic pagination with django
Okay so this is first time using pagination with Dajngo and I am trying to prevent it from reloading my view on each page turn. I'm handling the pagination in the view like this: page = request.GET.get('page', 1) print page paginator = Paginator(list(od.iteritems())[:24], 12) try: data = paginator.page(page) except PageNotAnInteger: data = paginator.page(1) except EmptyPage: data = paginator.page(paginator.num_pages) print data save_query_form = SaveQueryForm(request.POST or None) #if request.method == 'POST': if save_query_form.is_valid(): profile = save_query_form.save(commit=False) profile.user = request.user profile.save() context = { "title":"Search", 'data': data,#list(od.iteritems()), 'tools': od_tools.iteritems(), 'methods': od_methods.iteritems(), 'data4': od_data.iteritems(), 'search_phrase': " ".join(instanceValuesString), 'json_dump': js_data, 'form': save_query_form, } return render(request, 'results.html', context) and the pagination is handled in the html: {% if data.has_other_pages %} <div id='page-slide'> <ul class="pagination" start='$offset'> {% if data.has_previous %} <li><a href="?page={{ data.previous_page_number }}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} {% for i in data.paginator.page_range %} {% if data.number == i %} <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li> {% else %} <li><a href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if data.has_next %} <li><a href="?page={{ data.next_page_number }}">&raquo;</a></li> {% else %} <li class="disabled"><span>&raquo;</span></li> {% endif %} </ul> </div> {% endif %} The issue that I am having is that whenever I switch … -
About dictionary list
I want to fill a dictionary : recruitment_dict = {} for relation in Relation.objects.filter(on_team=Team.objects.get(owner=request.user)): if relation.recruitment is True: key = relation.on_game.guid value = [relation.on_plateform.guid, relation.recruitment] recruitment_dict[key] = value recruitment_dict returns this dictionary : {'A': ['b', True], 'B': ['b', True], 'C': ['b', True]} But some values are missing. Sometimes, I should have something like this : {'A': ['b', True], 'A': ['c', True], 'B': ['b', True], 'C': ['b', True]} I think the problem is because I use : recruitment_dict[key] = value And so, only the last object at the end of the boucle "for" is saved. But I don't know the right synthax to adopt. -
Django + Ajax . Can't find variable:ajaxPost
I downloaded a bit old project from repo(didn't updated it for few months) and it appeared ajax doesn't work somehow. In pip freeze I checked library I used djangoajax==2.4 In templates js code it looks like this: ajaxPost('/authfb/', {'username': fb_name , 'fb_id': fb_id, 'csrfmiddlewaretoken': getCookie('csrftoken')}, function(){ }); And issue in browser logs is that Can't find variable:ajaxPost I just don't know what that library was and maybe it's outdated? How to check? Or can be problem connected with something else? I am sure it worked before. All ajax, js, jQuery links and etc is correct -
How do I populate a hidden required field in django forms?
I looked at other similar questions on Stackoverflow, but those situations do not apply to me. I have a form with a Queue field that is a required field. This form is used in multiple places and in one such instance, I don't want the Queue field to be shown to the user. So, I simply did not render it on the template. But because this a required field, the form won't submit. How do I pre-populate this field while at the same time hiding it from the user? I cannot make changes to the model or the form's save methods because this form is also used at other places. forms.py class PublicTicketForm(CustomFieldMixin, forms.Form): queue = forms.ChoiceField( widget=forms.Select(attrs={'class': 'form-control'}), label=_('Queue'), required=True, choices=() ) views.py: def no_queue(request): if request.method == 'POST': form = PublicTicketForm(request.POST, request.FILES) form['queue'] = 9 # Tried to assign queue value to field, did not work if form.is_valid(): if text_is_spam(form.cleaned_data['body'], request): # This submission is spam. Let's not save it. return render(request, template_name='helpdesk/public_spam.html') else: form.save() else: form = PublicTicketForm(initial={'queue': 9}) # tried this one too, did not work either return render(request, 'helpdesk/no_queue.html', {'form': form}) The choices for this form were populated in the views, but because I'm not … -
Processing data from XML tags in python
I am trying to extract data from an XML document using python. The tool I'm currently trying with and seems like it is a stable choice is lxml. The issue I'm having is that the tutorials and questions I have came across all assume the format of the XML document is as follows: <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> With the values inside the XML tags. However - the document I am trying to extract from has values inside elements of the tags, like so: <note> <to id="16" name="Tove"/> <from id="341" name"Jani"/> <heading id="1" name="Reminder"/> <body id="2" name="Don't forget me this weekend!"/> </note> The way I have tried doing this in LXML is this: xml_file = lxml.etree.parse("test.xml") notes = xml_file.xpath("//note") for note in notes: note_id = note.find("id").text print note_id This just returns "None" I have now found that the .text is what gets data from inside the XML tags - However I simply can't find how to get the data from the elements shown above. Could anyone point me in the right direction? -
Django form field in if statement fail
I'm rendering a Django form using an if statement to construct the html template: {% for field in form %} {% if field.name == 'user_name' or 'phone' or 'email' or 'password1' %} <div class="col-12 col-md-6 col-lg-3"> <p class="text-left m-0 fs-13">{{ field.label_tag }}</p> {% render_field field class="form-control is-invalid" %} </div> {% else %} bla bla {% endif %} {% endfor %} But when I call the template, all fields are constructed using the if statement code, but I have fields like: location, birth_date... that are True in the else statement. What am I doing wrong? -
Overriding Django admin vs creating new templates/views
I am a total noob with Django, I come from the PHP world and I am used to doing things differently. I'm building an app and I want to change the way the backend looks, I want to use Bootstrap 4 and add a lot of custom stuff e.g. permission based admin views, and I was wondering what is the best practice, or how do more experienced django devs go about it? Do they override all the django.contrib.admin templates, or do they build custom templates and login/register next to it, and use the django.contrib.admin only for the superuser? What is the django way? -
Django MimeType error
guys, I have no idea what is wrong with this error. The code is not something that I wrote so I don't know much about it. Any help is greatly appreciated. I will update the question with any other information that you ask for when it is needed. The code is very hard to read an upload to stack overflow so code posts may take a long time to reply. Environment: Request Method: GET Request URL: http://192.168.2.214/accounts/login/?next=/ Django Version: 1.11.6 Python Version: 2.7.12 Installed Applications: ('django.contrib.auth', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'tsa.events') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'tsa.settings.ChapterMiddleware', 'django.contrib.messages.middleware.MessageMiddleware') Traceback: File "/usr/local/lib/python2.7/dist- packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File " /home/serverad/django14_project/my_django15_project/tsa/events/views.py" in login_view 185. next=request.GET.get('next', '/'), chapters=Chapter.objects.all(), error_msg=error_msg) File "/home/serverad/django14_project/my_django15_project/tsa/events/views.py" in render_template 71. return HttpResponse(txt, mimetype=kwds.get('mimetype','text/html')) File "/usr/local/lib/python2.7/dist-packages/django/http/response.py" in __init__ 301. super(HttpResponse, self).__init__(*args, **kwargs) Exception Type: TypeError at /accounts/login/ Exception Value: __init__() got an unexpected keyword argument 'mimetype' -
django image file not found . image name same as directory
In windows system if there is an image file named same as the parent directory name then django server does not show the image file. e.g: http://127.0.0.1:8000/a/a.jpg This url does not give any image. But when the same image is renamed as "b.jpg" http://127.0.0.1:8000/a/b.jpg This url gives the image. Note: This problem exists only when the django server is on windows operating system and browser - chrome. There is no problem with linux. -
Attribute Error when extending user model
I'm using Django 1.11 and Python 3. Currently I have my LDAP authentication working. However, I want to extend my user model and I'm getting the following error when attempting to extend my user model. AttributeError: 'User' object has no attribute 'profile' [25/Oct/2017 14:47:28] "POST /account/login/ HTTP/1.1" 500 224535 I've tried to change my code to user.profile or user.AllEeActive but then it gives me the following error: File "C:\python\security\accounts\models.py", line 52, in save_user_profile instance.username.save() AttributeError: 'str' object has no attribute 'save' [25/Oct/2017 14:43:31] "POST /account/login/ HTTP/1.1" 500 224521 Below is my models.py, what am I doing incorrect? from __future__ import unicode_literals from django.contrib.auth.models import User from django.db import models from django.forms import ModelForm from django.db.models.signals import post_save from django.dispatch import receiver import django_filters class AllEeActive(models.Model): employee_ntname = models.OneToOneField(User, db_column='Employee_NTName',max_length=12) # Field name made lowercase. employee_last_name = models.CharField(db_column='Employee_Last_Name', max_length=50, blank=True, null=True) # Field name made lowercase. employee_first_name = models.CharField(db_column='Employee_First_Name', max_length=50, blank=True, null=True) # Field name made lowercase. b_level = models.CharField(db_column='B_Level', max_length=10, blank=True, null=True) # Field name made lowercase. group_name = models.CharField(db_column='Group_Name', max_length=100, blank=True, null=True) # Field name made lowercase. r_level = models.CharField(db_column='R_Level', max_length=10, blank=True, null=True) # Field name made lowercase. division_name = models.CharField(db_column='Division_Name', max_length=100, blank=True, null=True) # Field name made lowercase. … -
how to do i automatically set the user field to current user in django modelform
How can i set the current login user to the user field of django model .In my view ,i am using function base view .My model is something like this . class create(models.Model): user=models.ForeignKey(User,related_name='create',unique=True) view.py def createform(reques): #help me -
AWS DMS migration causes null primary key error
i am using AWS RDS postgres database with django. I migrated the database to a new RDS postgres instance. I am able to connect to it through django and view all the records. But whenever I try to add records lets say new user it gives me # django.db.utils.IntegrityError: null value in column "id" violates not-null constraint # and some times i also get # Primary key (id) duplication error. # i dont understand, django is supposed to handle primary keys (id) and auto increments by default. It is strange why it is passing null while creating new records or why passing those keys which are already in use. I am unable to figure out what is wrong in whole process. It is simple homogenous DMS migration from postgres to postgres. Migration task completes successfully. It shows no errors. All the data and tables with public schema are replicated successfully. But i am unable to add new records to it. Note: I tried migrating db using "pg_dump" command and it worked fine. I was able to add records to it after migration. Also I tried using same postgres engine versions (9.5) on both instances. Any type of help would be … -
Django Channels. Adding users to a Group
I am coding kind of a social network app. I want to have users create conversations and add their friends to the conversation at creation of the conversation. They are going to receive messages via websocket. The problem that I have is that I can add users to listen to their conversations upon establishing websocket connection but how do I add a user's reply_channel to the Group of the newly created by some other user conversation (while the former user already has websocket connection established) so that they could start listening to incoming messages from the conversation? -
Create PostgreSQL Database on another Server using Django
I have a working local environment using Django 1.11 with a PostgreSQL 10 database running on Linux Mint. I am trying to take a copy of this environment and install it on two Ubuntu 16.04 development servers: one for the web server and the other for the SQL server. The problem is running Django with the Ubuntu PostgreSQL server. When I take the Django settings.py file, and change the server from 'localhost' to the IP address of the new PostgreSQL server, every command issued with manage.py fails. This includes createsuperuser, makemigrations and migrate. This fails on both my working, development machine and the new Ubuntu web server. Is there a step I am missing that should be done after changing the database server and before running a manage.py command? Everything I have read says to simply run the makemigrations, and migrate commands. I have even tried to delete the makemigrations folders, but still no luck. Verified: Can connect to the new PostgreSQL server remotely using the same user ID and password, and was able to create a table (so problem should not be related to security or remote access). Here is the (shortened) error that comes up each time: Traceback … -
socket.gaierror [errno 11004] django cassandra engine, Sync_cassandra error
File "C:\Python\Python35-32\lib\site-packages\cassandra\cluster.py", line 784, in <listcomp> for endpoint in socket.getaddrinfo(a, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM)] File "C:\Python\Python35-32\lib\socket.py", line 732, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno 11004] getaddrinfo failed what should I do to solve this error -
Styling UserForm in Django
I made a custom user form with fields username, password1 and pasword2, based on UserCreationForm. I want to style it using bootstrap form-control in Meta widgets, but it doesn't work. Is this possible? EDIT Although password1 and password2 are not in Meta fields, they are rendered. The code: class UserForm(UserCreationForm): class Meta: model = User fields = ['username'] widgets = { 'username': TextInput(attrs = { 'class': 'form-control', }), 'password1': PasswordInput(attrs = { 'class': 'form-control', }), 'password2': PasswordInput(attrs = { 'class': 'form-control', }), }