Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Many-To-Many Relationship (category)
My goal is to add categories to my Post model. I would like to be able to later query all post by different and sometimes multiple categories. models.py class Category(models.Model): categories = ( ('1', 'red'), ('2', 'blue'), ('3', 'black') ) title = models.CharField(max_length=50, blank=True, choices=categories) class Post(models.Model): text = models.CharField(max_length=500) category = models.ManyToManyField(Category) forms.py class Post_form(forms.ModelForm): categories = ( ('1', 'red'), ('2', 'blue'), ('3', 'black') ) category = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple, choices=categories) class Meta: model = Post fields = ( 'text', 'category' ) I'm confused on the logic of saving one obj before you can save another. views.py def post(request): if request.method == 'POST': form = Post_form(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.user = request.user p1 = Category(form.cleaned_data['category']) post.category.add(p1) return redirect('home:home') else: form = Post_form() args = {'form': form } return render(request, 'home/new_post.html', args) error: "<Post: Post object>" needs to have a value for field "id" before this many-to-many relationship can be used. -
How to open SQLite database using Datagrip in the Python Django web project?
I am trying to build a web project using Python Django. The first model has been created already. I try to open the default SQLite database using Datagrip, the procedure was shown in the screenshots, but it does not work. The error was :The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server. java.net.ConnectException: Connection refused. what should I do? Thank you for the help. Add an new database Test the connection -
DataTabels - How to remove top search bar? [duplicate]
This question already has an answer here: How can I remove the search bar and footer added by the jQuery DataTables plugin? 16 answers in datatables there is a search bar on top of the table and there is search bar on each column is it possible to remove the top search bar ? here's my js code : $('#table-1').dataTable({paging: false, bDeferRender: true, bProcessing: true}); var table = $('#table-1').dataTable(); $('#table-1 tfoot th').each(function (i) { var title = $('#table-1 thead th').eq($(this).index()).text(); var serach = '<input type="text" class="coulmnSearch" placeholder="جستجوی ' + title + '" />'; $(this).html(''); $(serach).appendTo(this).keyup(function(){table.fnFilter($(this).val(),i)}) }); -
Error update formatted sequence number table
i have code like this: class NumberSequence(models.Model): code = models.CharField(max_length=12) prefix = models.CharField(max_length=3, verbose_name='Prefix') length = models.IntegerField(verbose_name='Digit Length') last = models.IntegerField(verbose_name='Last Number Used') def getNumberSequence(): ns = NumberSequence.objects.filter(code='REQ') letter = ns[0].prefix lastNumber = ns[0].last+1 formatedNS = '{0}-{1:0'+str(ns[0].length)+'d}' NumberSequence.objects.filter(code='REQ').update(last=lastNumber) return formatedNS.format(letter,lastNumber) class Requisitions(models.Model): number = models.CharField(max_length=20, default=getNumberSequence) but when I created new record in Requisition, the last number in NumberSequence updated to lastNumber+2. example : last = 1. When i created new record, last updated to 3. The last should be updated to 2. What's wrong with my code? Thanks -
Django can not send email on Linux
I use Django to send email,everything is OK when running on development environment, which uses command "runserver" on my iMac. But in the production environment which deployed by nginx+uwsgi+Django is not work. In addition,my machine is CentOS 64,and fire wall is close.I am in a puzzle about this. -
ajax to send the variable by Restful Api
I am a rookie in the Restful,I want to send some variables to the viewset to response some filtering data,Now I have finished some parts ,I can get the all data,but I don't understand how to send data to a specific function , for example I crate a new function called "get_ajax_variable() " ,How could I to send variables(data) to the function ? appreciate in Advance! This is my Serializer class CompanySerializer(serializers.HyperlinkedModelSerializer): Brand = serializers.ReadOnlyField(source='brand_set.all', read_only=True) class Meta: model = Company fields = data_export_setting.Company_form_stand def create(self, validated_data): validated_data['owner'] = self.context['request'].user return Company.objects.create(**validated_data) this is my viewset class CompanyViewSet(viewsets.ModelViewSet): queryset = Company.objects.all() serializer_class = CompanySerializer this is my ajax,the function of "showTable(json)" is a function to reload my company.html <script type="text/javascript"> $(document).ready(function () { $('#ab').click(function () { var filter_2 = $("#insert_value").val();//for City var filter_1 = $("#insert_value_1").val();// for Company type var filter = $('#filter').val();//for search $.ajax({ type: "GET", data: {filter:filter, filter_1_value:filter_1,insert_value:insert_value}, url: "https://horizon-retail-sam-leon-ghibli.c9users.io/restful_api/companyviewset/?format=json", cache: false, dataType: "json", contentType : 'application/json', success: function (json) { $('#ajax_search').empty(); showTable(json); }, error: function () { alert("false"); } }); }); }); -
Django unable to detect the existance of a model's field
here is my model: class Question(models.Model): id = models.AutoField(primary_key=True) question_title = models.CharField(max_length=100, default="no title") question_text = models.CharField(max_length=200, default ="no content") def __unicode__(self): return self.question_title + self.question_text and in my admin configuration page, I setup my QuestionAdmin class like this: class QuestionAdmin(admin.ModelAdmin): fieldsets = [ ('Question ID', {'fields':['id_pk']}), ('Question content',{'fields':['question_title',"question_text"]}) ] and then I applied this configuration into django's admin page: admin.site.register(Question, QuestionAdmin) and here is my full error trace: Environment: Request Method: GET Request URL: http://www.whiletrue.cc/paradox/admin/polls/question/add/ Django Version: 1.11.2 Python Version: 2.7.12 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls.apps.PollsConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/usr/local/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in wrapper 551. return self.admin_site.admin_view(view)(*args, **kwargs) File "/usr/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/usr/local/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "/usr/local/lib/python2.7/site-packages/django/contrib/admin/sites.py" in inner 224. return view(request, *args, **kwargs) File "/usr/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in add_view 1508. return self.changeform_view(request, None, form_url, extra_context) File "/usr/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapper 67. return bound_func(*args, **kwargs) File "/usr/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/usr/local/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func 63. return func.__get__(self, … -
How does python logical OR evaluate list/dictionaries
I was under the impression that logical operators always returns a boolean value but recently I came across a code that does a OR with lists/dictionaries, so I decided to dig in further - when I performed an OR with two lists I could see the first list value returned always, I could use some help in understanding the behavior of this: value_one = [{'name': u'TEST', 'amount': 0.0}] value_two = [{'name': u'TEST', 'amount': u'0.00'}] print value_one or value_two # output: [{'amount': 0.0, 'name': u'TEST'}] Sorry if this is a silly question, I spent a couple of hours but I'm failing at Google search. Thanks in advance! -
Python Django | Importing views in urls.py
My urls.py looks like this : from django.conf.urls import include, url from django.contrib import admin from devicesfor import views from devicesfor.forms import LoginForm admin.autodiscover() list_patterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^', include('devicesfor.urls')), url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'devicesfor/login.html'}), url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/login'}), ] urlpatterns = [ url(r'^', include(list_patterns)), ] And the error I'm getting is TypeError: view must be a callable or a list/tuple in the case of include(). I understand that I have to import the view in your urls.py. Being a newbie, not super sure how I would modify the code and fit this in.. Appreciate your help! Many thanks!! -
Create a Gmail account in Django using Python?
I'm working on a Django project and wanted its users to have the ability to create a Gmail account directly through our site. Is anyone familiar with a way to do so? If not, I was thinking of embedding Google's account creation page directly into the Django site, but I'm still unsure of how to do that. Any suggestions would be great. Thanks! -
Django - How can i assign a value to a object using a formset but in a view
(Sorry for my bad english) I need to add a value to a object field, that i'm excluding from the formset. i like to auto assign this in a view. (i can't modify the model to add a def save method and make it there because is a third party app model) This is the model class Tax(models.Model): """A tax (type+amount) for a specific Receipt.""" tax_type = models.ForeignKey( TaxType, verbose_name=_('tax type'), on_delete=models.PROTECT, ) description = models.CharField( _('description'), max_length=80, ) base_amount = models.DecimalField( _('base amount'), max_digits=15, decimal_places=2, ) aliquot = models.DecimalField( _('aliquot'), max_digits=5, decimal_places=2, ) amount = models.DecimalField( _('amount'), max_digits=15, decimal_places=2, ) receipt = models.ForeignKey( Receipt, related_name='taxes', on_delete=models.PROTECT, ) def compute_amount(self): """Auto-assign and return the total amount for this tax.""" self.amount = self.base_amount * self.aliquot / 100 return self.amount class Meta: verbose_name = _('tax') verbose_name_plural = _('taxes') This is the form and formset class TaxForm(forms.ModelForm): class Meta: model = Tax fields = [ 'tax_type', 'description', 'base_amount', 'aliquot', ] ReceiptTaxFormset = inlineformset_factory( Receipt, Tax, form=TaxForm, extra=0, can_delete=False, ) And this is the part of the view where i handle the formset if form.is_valid() and entryFormset.is_valid() and taxFormset.is_valid(): receipt = form.save(commit=False) # Tomamos el punto de venta de la sucursal y lo asignamos … -
How to render word or pdf doc in Django template
` <div class="modal-body"> {% if forms|length == 1 %} {% for form, html in forms.items %} {% ssi html %} {% endfor %} ` below is the snapshot for rendering html -
Django: redirect url if slug is wrong
I have a function that is run every view to correct slugs. For example if the slug is /12-post-about-stuff and a user enters /12-post-abot_stof they will be redirected correctly. The problem is that the different views have different url patterns for example: /posts/post_slug/ ... /posts/post_slug/comments/new how to I write a function that redirects by fixing the slug name based on the current url? -
sorl thumbnail only displays img src but not the image
thumbnail generated with sorl-thumbnails only display this "src="/media/cache/14/20/142041c984706cb5770556b771a182e5.jpg" id="more">" but not an actual image Now my media_url and media_root are set to /media/ and os.path.join(BASE_DIR, 'media/') respectively and uploaded images images are saved in /media/ but thumbnails automatatically save at /media/cache/.... and my nginx conf for images(if it helps) is location /media/ { alias /home/kingiyk/stylplus/media/; } Images not generated by sorl-thumbnail(located at/media/) have no problem displaying. I am thinking this is a cache problem but dont know how to go about it. HELP -
How to export app metrics using prometheus client from an Django app running as an uwsgi server?
I read the docs of prometheus client https://github.com/prometheus/client_python/#multiprocess-mode-gunicorn where it mentions to expose metrics in a multi-process mode in python. Instead of Gunicorn, I am running django app via uwsgi. Similar to that in the docs I added code in my project's wsgi.py - class WSGIEnvironment(WSGIHandler): def __call__(self, environ, start_response): **registry = CollectorRegistry() multiprocess.MultiProcessCollector(registry) data = generate_latest(registry)** django.setup() return super(WSGIEnvironment, self).__call__(environ, start_response) application = WSGIEnvironment() But exposing collected data via this method did not look feasible to me. Hence I exposed an api in my Django app /metrics which invokes metrics view - def metrics(request): registry = CollectorRegistry() multiprocess.MultiProcessCollector(registry) data = generate_latest(registry) print "data", data return HttpResponse( data, content_type=CONTENT_TYPE_LATEST) Still I cannot view the metrics being exposed by my app. Is there any configuration required? I think I am missing very basic thing. -
How to set custom form attributes in Django
I want to abstract my post url form my view and template logic, so that the only reference to the api my form wants to call is the form itself. So far, I've set up a basic form with an input field that references a post url class PartSearchForm(forms.Form): search_term = forms.CharField( label="", widget=forms.TextInput( attrs={ 'id':'focusedElement', 'autofocus':'autofocus', 'onfocus':'this.value = this.value', 'placeholder':'enter a part id', 'post_url':'api_part_table_1' })) and I can access it through a jQuery function like this $( "input[type='text']" ).on('input', _.debounce(function() { var url = $(this).attr('post_url'); $.get(url, $(this).serialize(), function(data) { $('#' + url).html(data) console.log('posted to ' + url); }); }, 500)); I'm just using the post_url attribute of my textbox to submit the query. this works just fine on the debounce refresh, but I'd like to also be able to access this value on the form itself, so that I can refresh when the form is submitted $("form").bind('submit', function(e) { e.preventDefault(); var url = $(this).attr('post_url'); $.get(url, $(this).serialize(), function(data) { $('#' + url).html(data) console.log('posted to ' + url); }); }); so basically I just need to assign an attribute to the root django form class like I have in the forms.CharField so I can call it using the jQuery function .attr('post_url') -
Django or node.js which one is good for me? [on hold]
I'm new to web programming and don't have much info about it .I want to make an android app which can send and also gets information from a server for example an app which has some users and every user can mark a place on map and other users can see the markers on map when they get online or if they are online they should be able to see ot instantly and also they should be able to add markers too so for an app like this which one will have a better performance and its easier too work with django or node.js or tornado or totally something else? (im an android developer, i dont know python or javascript ) -
how to create django web page similar to admin site
I am a beginner in django and i want to create a new web page which i can edit and add to a database model like the admin site page but this will be in the website to enable the user to control it and i can extend my base.html page in it, I search for it and i didn't find a simple solution like admin base site that enable me to control the models, i tried to send all objects of this model in the context but i cant add or edit it in the database model, just i can view it only. can any one help me? thanks. This is my models.py for this web page: from django.db import models class Email(models.Model): type = models.CharField(max_length=200, null=True, blank=True) subject = models.TextField() from_email = models.CharField(max_length=200, null=True, blank=True) to_email = models.CharField(max_length=200, null=True, blank=True) reply_to_email = models.CharField(max_length=200, null=True, blank=True) body_text = models.TextField() body_html = models.TextField() status= models.CharField(max_length=200, null=True, blank=True,default='waiting') def __unicode__(self): return self.to_email class EmailTemplate(models.Model): template_name=models.CharField(max_length=200) subject = models.CharField(max_length=200) from_email = models.CharField(max_length=200, null=True, blank=True) reply_to_email = models.CharField(max_length=200, null=True, blank=True) body_text = models.TextField() body_html = models.TextField() def __unicode__(self): return self.template_name my views.py from django.http import HttpResponse from django.shortcuts import render_to_response from django.template import … -
django + postgres: case insensivity for unicode in serch_fields
On my dev server serch_fields in admin works with unicode queries in case insensitive mode, but the same code on production works only in sensitive mode. I think i have the same configurations with python 2.7.6, Django 1.9.4, PostgreSQL 9.5.7. I've just added to admin.py this: search_fields = (u'title', u'subtitle') Where the problem could be? (i'm newbie at all)insensivity -
Collecting Relational Data and Adding to a Database Periodically with Python
I have a project that : fetches data from active directory fetches data from different services based on active directory data aggregates data about 50000 row have to be added to database in every 15 min I'm using Postgresql as database and django as ORM tool. But I'm not sure that this is right way. (performance) Is there another way to do such process? -
Using PUBLIC_SCHEMA_URLCONF in django-tenant-schemas
I am trying to have django-tenant-schemas re-route users if they visit the base domain using the optional setting PUBLIC_SCHEMA_URLCONF. Whenever I visit the base url I get this response: I'm hoping someone can tell me what the value of PUBLIC_SCHEMA_URLCONF should be based on my project structure or if anything else might be wrong. I want to use the urls from public_website when people try to access the base domain. My project directory looks like this: website ├──approvals ├──batches ├──customauth ├──email_portal ├──exports ├──file_downloads ├──password_reset ├──payroll ├──payroll_codes ├──reports ├──scheduling ├──shifts ├──static ├──templates ├──website | ├──migrations | ├──static | ├──templates | └──settings | ├──__init__.py | ├──base.py | ├──prod.py | └──dev.py ├──scheduling ├──public_website | ├──__init__.py | └──urls.py └──manage.py And I want PUBLIC_SCHEMA_URLCONF to refer to the urls in public_website, which look like: from django.conf.urls import include, url import website.views as website_views from django.contrib import admin from django.http import HttpResponse url_patterns = [ url(r'^$', lambda request: HttpResponse('ok')), url(r'^admin/login/', website_views.Login.as_view()), url(r'^admin/', include(admin.site.urls)) # user authentication urls ] Here are the relevant bits in my settings: DJANGO_APPS = ( 'jet', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'django.contrib.admin', 'django_user_agents', 'django_ses', # 'admin_reorder' ) MY_APPS_WITH_MODELS = ( 'customauth', 'payroll_codes', 'scheduling', 'payroll', 'shifts', 'email_portal', 'tutor_training_tracker' ) MY_APPS_WITHOUT_MODELS = ( … -
Django ModelForm encode and instance error
I'm working with Django ModelForms and I got some problems with the Admin Form override. I created the next code to change the widget of my multichoice field. media_outlet = forms.ModelMultipleChoiceField( label= _(u'Media outlet'), queryset=MediaOutlet.objects.all(), widget=forms.CheckboxSelectMultiple() ) when I saved, I get this error: UnicodeDecodeError. Is there a way to validate or define the encode? and this another error when I select others value: "Entry.media_outlet" must be a "MediaOutlet" instance. Any idea whats it's happen? Thanks. -
django sorting table with pagination
I want to sort my table columns both ways (ascending and descending, switch upon pressing a button). The problem I have is my tables go out of order when I switch a page. views.py def company_index(request): order_by = request.GET.get('order_by') companies = Company.objects.all().order_by(Lower(order_by)) paginator = Paginator(companies, 10) page = request.GET.get('page') try: all_companies = paginator.page(page) except PageNotAnInteger: all_companies = paginator.page(1) except EmptyPage: all_companies = paginator.page(paginator.num_pages) return render(request, 'companies/company_index.html', {'all_companies': all_companies}) Here is how I display data in my templates (I shortened class names for better post visibility): <thead> <tr> <th>Company name <a class="glyphicon" href="?order_by=company_name"></a></th> <th>Company address <a class="glyphicon" href="?order_by=company_address"></a></th> <th>Tax ID <a class="glyphicon" href="?order_by=tax_id"></a></th> <th>Company ID <a class="glyphicon" href="?order_by=company_id"></a></th> <th>KRS Number <a class="glyphicon" href="?order_by=KRS_number"></a></th> </tr> </thead> My pagination code: <ul class="pagination"> {% if all_companies.has_previous %} <li><a href="?page={{ all_companies.previous_page_number }}&?order_by={{order_by}}">previous</a></li> {% endif %} <li class="disabled"><a>Page {{ all_companies.number }} of {{ all_companies.paginator.num_pages }}</a></li> {% if all_companies.has_next %} <li><a href="?page={{ all_companies.next_page_number }}&?order_by={{order_by}}">next</a></li> {% endif %} </ul> When I switch to other page {{order_by}} passes None. Also, how can I make it sort descending or ascending, after pressing a button? I want to do it without outside apps or libraries, to have a better understanding of django. -
Popup window when the page is closed
hello i have a Django base app and one of its apps is chatting with customer service. i want when the customer clicks on the the [x] icon or close the window, a small popup window should come up that include: 1.a string like "thank you, and we hope you can take time and answer the survey:" 2. a button that directs the customer to the survey page. i have this part of the chatting app java script file: window.onbeforeunload = function() { window.open ("http://gadgetron.store/male_chatbot/popup/"); <= i have tried it and it doesn't work $.ajax({ type: 'GET', url: 'http://gadgetron.store/chatbot/run_python_clear_chatM/',});} thank you, -
Django - Found another file with the destination path django - during deploying app
trying to deploy my app to uwsgi server my settings file: STATIC_ROOT = "/home/root/djangoApp/staticRoot/" STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), '/home/root/djangoApp/static/', ] and url file: urlpatterns = [ #urls ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) and if I try to execute the command: python manage.py collectstatic Then some files are okay ( admin files ), but I see an error next to files from static folder. The error is like: Found another file with the destination path 'js/bootstrap.min.js'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. and have no idea what can I do to solve it. Thanks in advance,