Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Display keys and values in template
I'm trying to display my dict values in my template, but I cannot properly handle one of the values. I'm not sure if it's the js file, the way I save the json or the template that's wrong. My template. {% for key1, values1 in products.products.items %} <div onClick="hello(this.id)" id="{{key1}}"> {{ values1 }} <----- Shows (1) {{ values1.pk }} <---- No show {% for key2, values2 in values1.items %} {{ values2 }} <---- No show {% endfor %} </div> {% endfor %} My view function. def createItem(request): form = itemCreateForm(request.POST) if form.is_valid(): model_instance = form.save(commit=False) model_instance.save() with open(BASE_DIR + '/kar/products.js', 'r+') as json_file: products = json.loads(json_file.read()) <--- Getting current values of json data = serializers.serialize('json', [model_instance,]) <-- Form to model instance struct = json.loads(data) data = json.dumps(struct[0]) products['products'][model_instance.pk] = data <--- updating current values print(products) json_file.seek(0) json_file.write(json.dumps(products)) <--- saving the updated values else: print('False') return HttpResponseRedirect('/homepage/CMS/') My products.js file {"products": { "102": "{\"pk\": 102, \"fields\": {\"price\": 31, \"name\": \"31\", \"type\": \"2\"}, \"model\": \"kar.item\"}", "103": "{\"pk\": 103, \"fields\": {\"price\": 22, \"name\": \"22\", \"type\": \"2\"}, \"model\": \"kar.item\"}" } } Running the above code will only display (1): {"pk": 103, "fields": {"price": 22, "name": "22", "type": "2"}, "model": "kar.item"} {"pk": 102, "fields": {"price": … -
For loop loops only once if there is function inside
I encountered a problem with my for loop. When there is function inside it loops only once, for the first item and this is it. If I comment-out the function it loops through all the items. This is the loop: for dev in devices: print(dev.device_id) emailNotification("[eTaborniki]: Novo sporočilo", str("Zadeva: "+msgsubject+"\r\n"+body_preview), str(dev.device_id)) And this is the function: def emailNotification(title, body, to): payload = { "to": to, "data": { "message": body, "title": title, "click_action": "https://****/sporocila", "icon": "https://****/images/logo-256.png" }, "from": FCM_ID } headers = { 'Content-Type': 'application/json', 'Authorization': FCM_KEY_HEADER, } r = requests.post('https://fcm.googleapis.com/fcm/send', data=json.dumps(payload), headers=headers) response = r.json() print(response) if response['results']['error'] is 'NotRegistered': token = PushDevices.objects.all().filter(device_id=to) token.delete() print("Token Deleted") -
How to override Django's User to return get_full_name() across project without extending User model
I want to overide the default return value of the Django User model to return get_full_name() instead of the default get_username(). That is the ONLY change I want to make to the model, and I don't want to create a custom User, as I already have a Profile model. The suggestion from this question looks like it would do it: from django.contrib.auth.models import User def get_first_name(self): return self.get_full_name() User.add_to_class("__str__", get_full_name) How can I put this, or something better, in settings.py to override this for my entire project? -
Django Autocreate Models
My Models: class Urunler(AnaModel): adi = models.CharField(max_length=128, verbose_name="Ürün Adı") aciklama = models.TextField(verbose_name="Açıklama") kategori = models.ForeignKey(Kategoriler, verbose_name="Kategori", related_name="urunler", null=True) agirlik = models.DecimalField(max_digits=6, decimal_places=2, verbose_name="Ağırlık", default=Decimal(1)) birim = models.CharField(max_length=2, choices=BIRIMLER, default="kg") class Stok(AnaModel): adi = models.ForeignKey(Urunler, related_name="stok", verbose_name="Ürün Adı") marka = models.CharField(max_length=256, verbose_name="Marka/Firma") stok_giris = models.DateTimeField(verbose_name="Stok Giriş Tarihi") uretim_tarihi = models.DateField(verbose_name="Üretim Tarihi", blank=True, null=True) sk_tarihi = models.DateField(verbose_name="Son Kullanma Tarihi", blank=True, null=True) irsaliye_no = models.PositiveIntegerField(max_length=32, verbose_name="İrsaliye No", blank=True) fatura_no = models.PositiveIntegerField(max_length=32, verbose_name="Fatura No", blank=True) adet = models.PositiveIntegerField(default=Decimal(1)) aciklama = models.TextField(verbose_name="Açıklama", null=True) class StokCikis(AnaModel): adi = models.ForeignKey(Urunler, related_name="stok_cikis", verbose_name="Ürün Adı") stok_cikis = models.DateTimeField(verbose_name="Stok Çıkış", blank=True, null=True, auto_now=True) teslim_alan = models.CharField(verbose_name="Teslim Alan", max_length=128, null=True, blank=True) aciklama = models.TextField(verbose_name="Açıklama", null=True, blank=True) adet = models.PositiveIntegerField(default=Decimal(0) When the product is created in "Urunler" models. Can "Stock" and "StockCikis" models be generated automatically? I want to create it with default values automatically. -
How to store a string that points to a boolean value in a django sqlite database
What I want to happen: I'm building a PTO(paid time off) App in django. I want the user to be able to choose between 4-5 different leave types such as "Jusry Duty", "Voting", "Emergency", etc etc and I want those strings to point to a True or False value that will determine whether or not the leave type is chargeable against the user's total PTO hours. The problem: The correct True or False value is saved to the database but when I view the record from within the django admin, if it is a True value it ALWAYS shows up as "PTO" and if it is a False value it ALWAYS shows up as "Jury Duty". I believe the reason it behaves like this is because "PTO" is the first True value in the tuple and "Jury Duty" is the first False value in the tuple. What I've tried: What I have right now is a boolean field on my PtoHistory model that takes in a tuple of LEAVE_CHOICES. class PtoHistory(models.Model): LEAVE_CHOICES = ( (True, 'PTO'), #is chargeable? (False, 'Jury Duty'), #is chargeable? (False, 'Voting'), #is chargeable? (False, 'Military Leave'), #is chargeable? (False, 'Bereavement'), #is chargeable? (True, 'Emergency'), #is chargeable? … -
Mapping JSON object with lodash
I'm trying to map a JSON object using lodash. I'm calling the json object as follows: var json = (function() { var json = null; $.ajax({ 'async': false, 'global': false, 'url': "{% url 'api_temp_income_statement' asset_details.id %}", 'datatype': "json", 'success': function (data) { json = data; } }); return json; }) Which returns a JSON object that looks like this: [{"model": "tempincomestatement", "pk": 3, "fields": {"income_period": "2016-01-31", "lease_income_collected": "994174.0000", "storage_income_collected": "236216.0000", "tax_income_collected": "131020.0000", "other_income_collected": "0.0000"} },... ] I'm trying to create a map that has an Income Period : remaining fields relationship, so "2016-01-31" : {"lease_income_collected" : "994174", ... } Reading the docs, it doesn't really address how to go about this...How would I accomplish this? -
GeoDjango OSMGeoAdmin cannot create new polygon in admin interface
I am using OSMGeoAdmin with a PolygonField. If one of my PolygonFields is null, the map shows up in the admin interface, but I cannot draw a new region. An area gets selected, but the polygon does not save and there is no option to save the points on the field. I am able to edit an existing region: But the tool does not seem to work on an empty polygon. -
How to change a language's label in Django language specific URLs using i18n_patterns?
I'm using Django's i18n_patterns, so my URLs look like www.domain.com/pt/title. I want to change the language code in the URL to a different string, say, for example 'br' instead of 'pt', so the same url above would be rendered www.domain.com/br/title. I only want to change the language's label, not the actual translation. -
Django TinyMCE Image Upload
I have TinyMCE in my Django website, without using Django App called django-tinyMCE, i just used CDN because app has problems with admin panel, anyways i'm trying to select and upload image from editor, by adding image plugin from init function because its uses image source a url by default. this is what i have: <script src="//cdn.tinymce.com/4/tinymce.min.js"></script> <script> tinymce.init({ selector:'textarea', plugins: [ "advlist autolink lists link image charmap print preview anchor", "searchreplace visualblocks code fullscreen", "insertdatetime media table contextmenu paste" ], file_browser_callback: function(field_name, url, type, win) { // file upload callback } }); so how can i select and upload image with django using Tiny-MCE, can you show me exactly how its done? i'm confused -
Django project works locally but not when deployed to Heroku
Django project works locally but not when deployed to Heroku. I'm getting this error: ImportError at / No module named 'inkbook.urls' Exception Type: ImportError Exception Value: No module named 'inkbook.urls' (Yes, I still have DEBUG=True, I know I'll need to change this.) Python 3.5.1 My requirements.txt dj-database-url==0.4.1 Django==1.10.4 gunicorn==19.6.0 whitenoise==3.2.2 psycopg2==2.6.2 I followed this guide: https://devcenter.heroku.com/articles/deploying-python and this one: https://devcenter.heroku.com/articles/django-app-configuration When I run heroku local web localhost:5000 functions perfectly. I've deployed using git push heroku master but get the above error when I go to the actual live website. Here's the url to the App that is giving me issue. I'm not sure if there is anything in there that is the problem though, I suspect it might be someplace else: github.com/desult/inkbook I have found similar issues and the solution for some have been to edit ROOT_URLCONF = 'mysite.urls' to ROOT_URLCONF = 'urls' . That doesn't seem to work for me, nor does it make sense that it would work. My Root urls.py: from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^inkbook/', include('inkbook.urls', namespace='inkbook')), ] My inkbook.urls: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.home, name='home'), ] When I … -
Django - saving onetonone linked forms at same time not working
I've have the following forms: class UpdateProfile(forms.ModelForm): username = forms.CharField(required=True) email = forms.EmailField(required=True) first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name') def clean_email(self): username = self.cleaned_data.get('username') email = self.cleaned_data.get('email') if email and User.objects.filter(email=email).exclude(username=username).count(): raise forms.ValidationError('This email address is already in use. Please supply a different email address.') return email class UserDetailForm (forms.ModelForm): linked_user = forms.CharField (required = True) linked_password = forms.CharField (required = True, widget = forms.PasswordInput()) connections = forms.IntegerField (required = True) class Meta: model = User_detail fields = ('linked_user','linked_password','connections') I'm trying to save them at the same time if both valid using: if request.method == 'POST': form = UpdateProfile(request.POST, instance=request.user) linked_form = UserDetailForm(request.POST, instance=request.user) if all((form.is_valid(),linked_form.is_valid())): user = form.save() linked = linked_form.save(commit=False) linked.user = user linked.save() msg = "Profile Updated" else: return error(request) This is the User_detail model: class User_detail (models.Model): user = models.OneToOneField ( User, on_delete = models.CASCADE ) linked_user = models.CharField ( verbose_name = 'LinkedIn Username', max_length = 50, ) linked_password = models.CharField ( max_length = 50, verbose_name = 'LinkedIn Password', ) connections = models.IntegerField ( verbose_name = 'Connections per day', default = 24, ) def __unicode__(self): return u'%s' % (self.user.first_name + ' ' + self.user.last_name) The … -
How do I get my Django generic view to work
Am I going about this the right way? Having never used 'generic views' I am tying to use Django's generic.UpdateView view. When I 'hit' the 'update' button on the form, I get an invalid form response with message 'Library with this Slide name already exists' Grateful for any help. View: class Slideview(generic.UpdateView): model = Library template_name = 'app1/slide_update.html' fields = ['slide_name', 'reference_value','esd', 'current_mean', 'counts_averaged', 'status'] context_object_name = 'qc_slide' #def get_queryset(self): #slide_id = self.kwargs['pk'] #return Library.objects.filter(slide_name=slide_id) def get_success_url(self): return reverse('Slideview', args=[self.kwargs['pk']]) def get_context_data(self, **kwargs): context = super(Slideview, self).get_context_data(**kwargs) #form = self.get_form(self.get_form_class()) #context['form'] = form return context def post(self, request, *args, **kwargs): print("Im in post") form = self.get_form(self.get_form_class()) if form.is_valid(): #Code will go here which will query a second model #perform a series of math calculations and then #return the updated information self.object = self.get_object() self.object.save() return self.form_valid(form) else: print("Form not valid") self.object = self.get_object() return self.form_invalid(form) Model: class Library(models.Model): slide_name = models.CharField(max_length=5, primary_key=True) reference_value = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal(0)) esd = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal(0)) current_mean = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal(0)) counts_averaged = models.IntegerField(default=0) status = models.CharField(max_length=9) def __str__(self): return self.slide_name -
Send SMS to each number in Django Database
Having trouble sending an SMS with python/django/twilio to employees in a table where each employee has an "admin" relationship Table Employees contains: fname, lname, phone_number, group views.py def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): cd = form.cleaned_data client = twilio.rest.TwilioRestClient('xx...', 'xxx...') recipients = employees.objects.filter(group__contains='admin') for number in recipients: client.messages.create(body='Sample text',to=number, from_='xxxxxx') return HttpResponseRedirect('/contact/thanks/') else: form = ContactForm() return render(request, 'contact_form.html', {'form':form}) The 'recipients'.... line in my code seems to be the culprit. I am getting a ValueError: data should be an integer, binary, or string, or sequence. models.py from django.db import models class employees(models.Model): fname = models.CharField(max_length=30) lname = models.CharField(max_length=40) email = models.EmailField() phone_number = models.CharField(max_length=15) group = models.CharField(max_length=20) def __str__(self): return self.phone_number Any help is appreciated! Thanks -
Django Template Remainder Error
I am using Django to and Google Calendar's API to process some user data. So I have some code here copied from one of the examples on the quickstart guide. (https://developers.google.com/google-apps/calendar/quickstart/pythondef def index(request): credentials = get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('calendar', 'v3', http=http) now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time print('Getting the upcoming 10 events') eventsResult = service.events().list( calendarId='primary', timeMin=now, maxResults=10, singleEvents=True, orderBy='startTime').execute() events = eventsResult.get('items', []) #Commented out the below parts because I want to pass these variables into the index.html page #if not events: # print('No upcoming events found.') #for event in events: # start = event['start'].get('dateTime', event['start'].get('date')) # print(start, event['summary']) return render(request, 'calendarfunction/index.html', {'events': events})) From my understanding, I am passing a dictionary called events to the index.html file and in my html file I can do something like this: {% for event in events %} <div>{{% event['start'].get('dateTime', event['start'].get('date')) %}}</div> {% endfor %} But I get a syntax error: Could not parse the remainder: '% event['start'].get('dateTime', event['start'].get('date')) %' from '% event['start'].get('dateTime', event['start'].get('date')) %' -
In Django how can I run the same function from views multiple times without refreshing the page?
On one of my pages in my web app, I want to be able to view the disk space left on the server & I want that information to update every 30 seconds they are on the page. So far I was able to create a button that runs the function and displays the results, however, I have been unsuccessful in finding a way to call that function automatically. I have tried 'sched' with no luck and when I tried using a loop, it just slowed down my server. Any feedback or advice would be greatly appreciated! Thanks -
No module named django urls for any django-admin command
I'm having trouble running Django on my company's server. When I try to start a project, like django-admin startproject newproject, it gives me: File "/opt/packages/anaconda/lib/python2.7/site-packages/django/__init__.py", line 18, in setup from django.urls import set_script_prefix ImportError: No module named urls When I run python and import django; django.VERSION, I get (1, 10, 2, u'final', 0). (I recently downgraded to 1.9.5 to match my company's version). And of course the company runs 1.9.5 from which I checked from pip list. Shouldn't I get 1.9.5 also when I call for the version in python? Here is my profile also: python='/opt/packages/anaconda/bin/python' export PATH=/opt/packages/anaconda/bin:$PATH export LD_LIBRARY_PATH=/opt/packages/anaconda/lib:$LD_LIBRARY_PATH export TCL_LIBRARY=/opt/packages/anaconda/lib/tcl8.5 -
Move m2m field to opposite model
I have 2 models with symmetric m2m field: class App1Model(models.Model): app2_model_objects = models.ManyToManyField( 'app2.App2Model', related_name='app1_model_objects') class App2Model(models.Model): pass I want to move that field into opposite model (to simplify processing of App2Model model forms): class App1Model(models.Model): pass class App2Model(models.Model): app1_model_objects = models.ManyToManyField( 'app1.App1Model', related_name='app2_model_objects') How to make safe migration of schema and data? -
Django Celery RabbitMQ mod_wsgi broker not work
I built a Django Celery application with RabbitMQ as broker and I've a problem on application deployment. this is my settings.py: # CELERY STUFF BROKER_URL = 'amqp://guest@localhost//' CELERY_RESULT_BACKEND = 'db+sqlite:///celerydb.sqlite' CELERY_RESULT_SERIALIZER = 'json' I built a celeryd script for celery daemon like documentation Daemonization All works fine with 'runserver' but on mod_wsgi apache deploy no. On Apache deployment if I watch at celery daemon log file I see tasks are invoked: Received task: load_civici_data[838de447-12fa-4a1f-be92-a5ea36a1c919] and result and state write in to celerydb.sqlite, but in my django application do not return tasks result like in runserver mode. Every tasks results 'PENDING'. Someone can help me? Thanks in advance Walter -
Django admin and autocomplete-light - how to override save method
I'm trying to include Django-autocomplete-light in my project. Everything works as expected including the creation of new choice by autocomplete. The only problem is my model contains more than one field and I'm using autocomplete only on the 'name' field. When I save my new record django-admin creates new object with the same name in the database instead of updating the record already created by autocomplete. At the end I have two records, one half empty created by autocomplete, and one valid created by django-admin. models.py class Montinent(models.Model): name = models.CharField(max_length=250) code = models.CharField(max_length=2, unique=True, db_index=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-name',) def __str__(self): return self.name views.py class MontinentAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): #Don't forget to filter out results depending on the visitor ! if not self.request.user.is_authenticated(): return Montinent.objects.none() qs = Montinent.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs urls.py urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^montinent-autocomplete/$', MontinentAutocomplete.as_view(create_field='name'), name='montinent-autocomplete',), ] admin.py class MontinentForm(forms.ModelForm): name = forms.ModelChoiceField( queryset = Montinent.objects.all(), widget = autocomplete.ModelSelect2(url='montinent-autocomplete') ) class Meta: model = Montinent fields = ['name', 'slug', 'code'] class MontinentAdmin(admin.ModelAdmin): form = MontinentForm admin.site.register(Montinent, MontinentAdmin) The way autocomplete creates new choice is as follow: When the user selects that option, the autocomplete script will make a … -
"Invalid tuple size in creation of Decimal from list or tuple" on DecimalField update
I have the following model: class Invoice(models.Model): debt = models.DecimalField(max_digits = 11, decimal_places = 2) When I try to update already existing Invoice: invoice = get_object_or_404(Invoice, pk=invoice_id) invoice.debt = '0' invoice.save() I get following error: 'Invalid tuple size in creation of Decimal from list or tuple. The list or tuple should have exactly three elements.' I tried invoice.debt = 0, invoice.debt = Decimal('0'), invoice.debt = 0.0, invoice.debt = Decimal('0.0') always the same error on invoice.save() Any ideas? Django 1.10.4, Python 3.4.3, Database in use MySQL 5.5.53-0ubuntu0.14.04.1 -
select jeditable with django
I'm discovering Jeditable and need to use a select field coming from my db $( ".editable" ).editable( "{{ set_job }}", { indicator : 'Saving...', tooltip : 'Click to edit...', type : "select", data : "{ {% for name in contacts_name %}'{{ name }}' : '{{ name }}', {% endfor %} }", submit : "ok", onblur : "submit" }) With something like contacts_name = Contact.objects.filter(myfilter) set_job = reverse(...) In my view But when I click on my field in my browser, the only thing that appear is an 'ok' submit button What did I miss ? -
Upload a file in azure
I want to upload images in Microsoft azure through a python script and show those images in a dashboard build on django admin interface. Now, i figured since i am sending pics i should be using ftp.. So this is the code: import ftplib session = ftplib.FTP('server.address.com','USERNAME','PASSWORD') file = open('kitten.jpg','rb') # file to send session.storbinary('STOR kitten.jpg', file) # send the file file.close() # close file and FTP session.quit() Now, i don't know how to setup ftp server in azure and how would i be able to fetch those images from server to my dashboard.. I don't know much about deployment so any link to do this or guide would be welcome/helpful. -
How to upload image to custom location using models.ImageField and attribute?
I am an absolute beginner with Django so here is my question: I created a model and I have image = models.ImageField(). When I use the admin interface, every uploaded image is placed in the root directory. I read through this https://docs.djangoproject.com/en/dev/topics/files/ and if I use the below example it still doesn't work. from django.core.files.storage import FileSystemStorage fs = FileSystemStorage(location='/static/images/gallery') class Car(models.Model): ... photo = models.ImageField(storage=fs) The new entry is correctly added but when I click the image name, the following error is displayed, and the image is not placed in /static/images/gallery Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/admin/Library/book/12/change/002_user_experience_remastered.jpg/change/ Raised by: django.contrib.admin.options.change_view book object with primary key '12/change/002_user_experience_remastered.jpg' does not exist. 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. What am I doing wrong? What am I missing? Thank you! -
Bootstrap form horizontal : button doesn't work
It's the first time I'm using Bootstrap. I need it to improve my Django script and more particularly HTML templates. But, since I wrote bootstrap code in my script, buttons don't seem to work : <h1 align="center"> Formulaire d'acte de naissance </h1> <br></br> <h3> Formulaire permettant la création de l'acte de naissance : </h3> <br></br> <form class = "form-horizontal" method='POST' action=''> {% csrf_token %} {% include "bootstrap_form_horizontal.html" with form=Bform %} <input class="button" type ="submit" name="_save2" value="Valider l'acte de naissance" /> <input class="button" type ="submit" name="_preview2" value="Prévisualiser l'acte de naissance" /> <form method='POST' action="{% url "home" %}"> {% csrf_token %} <input class="button" type ="submit" name="retour" value="Retour" /> </form> </form> <div class="form-group"> <div class="col-sm-10 col-sm-offset-2"> </div> </div> Do you have an idea ? I'm really lost even if I already read lot of documentations. Thank you ! -
Can you use .filter and .get in the same query for Django?
I have a database where data is organized by a number that is unique, and a name that isn't unique. for example: NumCOL: NameCOL: 1 Jay 2 Joel 3 Joey 4 Joel Could I use a filter and get statement to grab names where the number is equal to a certain number? Let's say I have a form that lets a user pick a number from the database and the user picks the number 2. num = request.POST.get('FormNumber') #num = 2 name = Database.objects.filter(NumCOL=num).get('NameCOL') return HttpResponse(name) Can something like this be done? I want to grab the name wherever the user selects based on their number. Based on the code I should get a response Joel. Thanks for your help!