Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Attribute Error: 'NoneType' object has no attribute 'id'
I have reached till chapter 4 of the Mozilla Django tutorial, but then I met with this error.I followed everything as it said but it is giving me this error when I tried to open the BookInstance model from the admin panel : AttributeError at /admin/catalog/bookinstance/ 'NoneType' object has no attribute 'id' Here is my code, models.py( The error occurs at the last line of the code) : from django.db import models from django.core.urlresolvers import reverse class Book(models.Model): """ Model representing a book (but not a specific copy of a book). """ title = models.CharField(max_length=200) author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True) # Foreign Key used because book can only have one author, but authors can have multiple books # Author as a string rather than object because it hasn't been declared yet in file. summary = models.TextField(max_length=1000, help_text="Enter a brief description of the book") isbn = models.CharField('ISBN',max_length=13, help_text='13 Character <a href="https://www.isbn-international.org/content/what-isbn">ISBN number</a>') genre = models.ManyToManyField(Genre, help_text="Select a genre for this book") # ManyToManyField used because Subject can contain many books. Books can cover many subjects. # Subject declared as an object because it has already been defined. def display_genre(self): """ Creates a string for the Genre. This is required to display … -
Can I use Celery v4.0.2 with Django v1.7.1 without using djcelery?
Currently I'm working on a Django project which is using version 1.7.1 and cannot be upgraded. I want to know whether I can use the latest version (4.0.2) of Celery with this project without using djcelery? -
'QuerySet' object has no attribute ''cantidad_update"
how are you? I have this error when trying to subtract the values in an IF where it is subtracted if the quantity_update is greater than 0. and if it does not subtract only the quantity. models.py: class Pedido(models.Model): especialidad = models.ForeignKey('Especialidad') articulo = models.ForeignKey('Articulo') fecha_entrega = models.DateTimeField(auto_now_add=False, null=True, blank=True) fecha_pedido = models.DateTimeField(auto_now_add=False,null=True, blank=True) cantidad = models.IntegerField(blank=True, default=0) estado = models.CharField(max_length=20, blank=True) cantidad_update = models.IntegerField(blank=True, default=0) estado_update = models.CharField(max_length=20, blank=True) class Articulo(models.Model): cod_experto = models.CharField(max_length=999, primary_key=True, blank=True) nombre = models.CharField(max_length=999, blank=True) on_delete=models.CASCADE) stock = models.IntegerField(blank=True, default=0) Views.py Query: def Entregar(request, id_especialidad): if request.method == 'GET': especialidad = Especialidad.objects.get(id=id_especialidad) pedido = Pedido.object.filter(especialidad=especialidad).filter(estado='pendiente') if pedido.cantidad_update > 0: #Here is the error! pedido.articulo.stock -= pedido.cantidad_update else: pedido.articulo.stock -= pedido.cantidad pedido.save() pedido2 = Pedido.objects.filter(especialidad=especialidad).filter(estado='pendiente').update(estado='entregado').update(fecha_entrega=datetime.date.today()) return HttpResponseRedirect('/solicitar/lista_super/%s/' % id_especialidad) This would be relevant and I do not know that I'm missing, some help please! -
Django user validation fail just gives 500 Server Error
Let's saying I'm adding a user and I want to fail it for some arbitrary reason. in signals.py, def user_presave_handler(sender, instance, **kwargs): raise ValidationError('You are a bad person') pre_save.connect(user_presave_handler, User) The webpage that the user sees is (500) Internal Server Error How do I make that instead notify the user of what went wrong? Thanks! -
'tuple' object has no attribute 'startswith'
i am trying to paly around with this old open sourced app , but i am getting error everytime i try to add a new invoice instance , and the error stats that : AttributeError at /admin/invoices/invoiceheaders/add/ 'tuple' object has no attribute 'startswith' views.py @login_required def new(request): error = '' if request.method == 'POST': itemFound = False for id in range(1, int(request.POST['numberitem']) + 1): if request.POST.get('Item_%s' %id): itemFound = True break if itemFound: user = User.objects.get(id = request.user.id) issuer = Contacts.objects.get(id = int(request.POST['Issuer']) ) customer = Contacts.objects.get(id = int(request.POST['Custumer']) ) payterm = Payterms.objects.get(id = int(request.POST['Payterm']) ) ihd = InvoiceHeaders() ihd.user = user ihd.issuer = issuer ihd.payterm = payterm ihd.customer = customer ihd.status = 'D' ihd.findrandomnumber=sha224( "%f"%(time()) ).hexdigest() ihd.save() for id in range(1, int(request.POST['numberitem']) + 1): if request.POST.get('Item_%s' %id): ibd = InvoiceBodies() ibd.header = ihd ibd.quantity = float(request.POST['Item_qta_%s' %id].replace(',','.')) items = Items.objects.get(id = int(request.POST['Item_%s' %id]) ) ibd.item = items ibd.extraDescription = request.POST['Item_descr_%s' %id].strip() ibd.save() return HttpResponseRedirect(reverse_lazy('invoices:index')) else: error = _('Item is obbligatory') form = formInvoice(uid=request.user.id) # An unbound form custumer_selected = 3 return render(request, 'invoices/new2.html' , {'form': form, 'custumer_selected' : custumer_selected , 'error' : error, }) models.py def content_file_name(instance, filename): return '/'.join([MEDIA_URL_USER_DOCS, '1' , filename]) class InvoiceHeaders(models.Model): issuer = models.ForeignKey(Contacts, related_name='invoices_issuer', … -
How to consume Django Rest Framework with a simple python application
I need to make a python app to make a connection with the API The python app is gonna send the user's ID to the API, then it's gonna get some informations about this user, such as their name, whether they are authenticated and so on. I already know how to create the rest api, But I don't know how to consume it. Thanks. -
Are Django sessions safe for a SSO authentication?
I'd like to implement sort of Single Sign On for several application using LDAPs and Django session, is that something doable, for at least one browser instance? Once I'm connected to the Django instance, I set a Session Variable reachable in the browser session used to connect through Django instance. Are there any known issues with this kind of authentication system? -
Update with condition in Django
I have a list of id and sort: ids = ['123', '456', '789', '901']; sorts = [1, 3, 2, 4]; I want to update the order of each id in Django. Here is the SQL and Django i have tried: SQL: UPDATE "Blogs" SET sort = CASE WHEN id = '123' THEN 1 WHEN id = '456' THEN 3 WHEN id = '789' THEN 2 WHEN id = '901' THEN 4 END WHERE id IN (ids); Django: Blogs.objects.filter( id=ids ).update( sort=Case( When(id=123, then=1), When(id=456, then=3), When(id=789, then=2), When(id=901, then=4), ) ) But problem is when ids have many elements I can not specific id and then in When(id={id}, then={sort}). How can I optimize the update query in Django version. Thanks in advance. -
Creating Django pgSQL Query With COUNT , GROUP BY , INTERVAL and LIMIT
I am trying to create the following query in Django SELECT content_reference , COUNT(reference) AS total FROM usage_statistics WHERE content_type = 'blog' AND access_date > NOW() - INTERVAL '90' DAY GROUP BY content_reference ORDER BY total DESC LIMIT 10 What I've figured out so far is: result = UsageStatistics.objects.all().values('content_reference').annotate(total=Count('reference')).order_by('total') This makes the query SELECT "usage_statistics"."content_reference", COUNT("usage_statistics"."reference") AS "total" FROM "usage_statistics" GROUP BY "usage_statistics"."content_reference" ORDER BY "total" ASC LIMIT 21 I am unsure how to correctly include: AND access_date > NOW() - INTERVAL '90' DAY ORDER BY total DESC The following is my usage_statistics table structure CREATE TABLE usage_statistics ( reference bigint access_date timestamp with time zone, ip_address inet NOT NULL, language_iso text NOT NULL, content_type character varying(12) NOT NULL, content_reference text NOT NULL, passport_user_id bigint ) -
How do I get values of the second, third, nth pass in a django template for loop?
I have the following code in my template: {% with element=vals|first %} #can use last here to get the last value {% for key,value in element.items %} <td>{{ value.corr }}</td> <td>{{ value.str }}</td> <td>{{ value.sig }}</td> {% endfor %} {% endwith %} That will give me the first values in the first iteration of the loop. How do I get the second, third, and nth? I'd thought about using slice, but that doesn't seem to work here -- or I'm not formatting the slice correctly. Please help! -
attempt to import csv using django-import-export results in tablib.core.InvalidDimensions
I am trying to import some csv data into a postgresql database using django-import-export. I am using python 3.4, django 1.8.1, and import-export 0.5.1. My settings file has the following directive: IMPORT_EXPORT_USE_TRANSACTIONS = True my model has 10 fields. Postgresql autoincrements an 11th field, the id. class BankTransaction(models.Model): tacct = models.ForeignKey(MetaAcct,on_delete=models.CASCADE) tdate = models.DateTimeField('tdate') tctpty = models.ForeignKey(Counterparty,on_delete=models.CASCADE) TRANSACTOR_CHOICES = ( ('XXX', 'transactor1'), ('YYY', 'transactor2'), ) tuser = models.CharField(max_length=3,choices=TRANSACTOR_CHOICES,default="LMH") # eg LMH trec = models.IntegerField(default=0, blank=True) tnote = models.CharField(default='',max_length=50, blank=True) tcheckno = models.IntegerField(default=0, blank=True, null=True) ttype = models.ForeignKey(TransactionType,on_delete=models.CASCADE) tamt = models.DecimalField(max_digits=10, decimal_places=2) tmemo = models.CharField(default='',max_length=20, blank=True) def __str__(self): label = str.join(',',(str(self.tacct),str(self.tctpty))) return label In admin.py I whitelist 8 fields, including the id field: from django.contrib import admin from import_export import resources from .models import MetaAcct,Counterparty,TransactionType,BankTransaction admin.site.register(MetaAcct) admin.site.register(Counterparty) admin.site.register(TransactionType) admin.site.register(BankTransaction) class MetaAcctResource(resources.ModelResource): class Meta: model = MetaAcct class BankTransactionResource(resources.ModelResource): class Meta: model = BankTransaction fields = ('id','tacct','tdate','tctpty','tuser','trec','ttype','tamt') My shell commands come right out of Read-the-docs: >>> import tablib >>> from import_export import resources >>> from mny.models import BankTransaction >>> banktransaction_resource = resources.modelresource_factory(model=BankTransaction)() >>> dataset = tablib.Dataset(['','/Users/userid/Downloads/pa upload/test.csv'], headers=['id','tacct','tdate','tctpty','tuser','trec','ttype','tamt']) The file I am trying to import, test.csv, looks like this: id,tacct,tdate,tctpty,tuser,trec,ttype,tamt ,test,2015-01-13 0:00:00,TEST_ACCT,XXX,20151031,xfer,20000 ,test,2015-01-31 0:00:00,BANK_ACCT,XXX,20151031,Int Inc,0.09 ,test,2015-11-30 0:00:00,BANK_ACCT,XXX,20151130,Int Inc,1.49 ,test,2015-12-17 0:00:00,TEST_ACCT,XXX,20151231,xfer,12000 ,test,2015-12-31 0:00:00,BANK_ACCT,XXX,20151231,Int … -
Import JSON file to JavaScript function
Is it possible to import a JSON file into a JavaScript function? If yes, how can this be done the best practice way? Below is my code with a few json rows and It'd be insane to have a million rows hardcoded in the function. <script> $( function() { var availableTags = [ "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme" ]; $( "#tags" ).autocomplete({ source: availableTags }); } ); </script> -
Setting django psfield Datetimerange fails with invalid input syntax for type timestamp with time zone
Using django 1.10 I am trying to save a form of a model which contains a Datetimerange (postgres specific field). The form validates, but saving it will let the time_range_for_delivery empty in the model's object. So I try to set it again after validating the form. But when I try to save the model, I get this error: invalid input syntax for type timestamp with time zone: "[" LINE 1: ...= 'chosen', "time_range_for_delivery" = tstzrange('[', 'd', ... POST data seems fine: time_range_for_delivery= ('[datetime.datetime(2017, 4, 10, 0, 25, 23, 414951, tzinfo=<UTC>), ' 'datetime.datetime(2017, 4, 10, 2, 25, 23, 414983, tzinfo=<UTC>)]') models class Order(AuditMixin): time_range_for_delivery = psfields.DateTimeRangeField( _('Período de entrega'), help_text=_('Quando será a entrega'), blank=False, null=True ) forms class OrderFinalForm(ModelForm): start = datetime.datetime.now() end = datetime.datetime.now()+datetime.timedelta(hours=2) choices = [ ([start, end], start.strftime('%A - %d/%m/%Y')\ + ' das '+start.strftime('%H:%m')\ + ' às '+end.strftime('%H:%m')) ] time_range_for_delivery = ChoiceField(choices, required=True, ) views def post(self, *args, **kwargs): chosen_order = Order.objects.get(pk=self.request.POST['choice']) form = OrderFinalForm(self.request.POST, instance=chosen_order) if form.is_valid(): self.order = form.save(commit=False) self.order.time_range_for_delivery = list(form.cleaned_data['time_range_for_delivery']) -
Issue with displaying foreign key field in a form
I'm trying to make a form that will register a new event. The model contains a foreign key of "Address". I am unable to get it to display its fields and right now it produces a drop down box that is just contains "-------".I've read the documentation and several other sources, but I don't understand the inner workings of doing this. It seems really complicated to do something small. forms.py from django import forms from .models import Show, Address from django.forms.models import inlineformset_factory class Submit_Event_Form(forms.ModelForm): class Meta: model = Show exclude = ('date_created',) fields = ['show_date', 'show_address'] Address_Form_Set = inlineformset_factory( Address, Show, fields='__all__') models.py from django.db import models from django.utils import timezone class Address(models.Model): """Address model - contains properties for Address""" address_street = models.CharField(max_length=200) address_city = models.CharField(max_length=200) address_state = models.CharField(max_length=2) address_zip = models.IntegerField() class Show(models.Model): """Show model - contains properties for Shows""" BOX_CHOICES = ( ('box', 'BOX'), ('gred', 'GRED'), ('boxgred', 'BOX/GRED')) date_created = models.DateTimeField( default=timezone.now) show_date = models.DateTimeField() show_address = models.ForeignKey( Address, on_delete=models.CASCADE,) views.py def event_add_view(request): if request.POST: form = Submit_Event_Form(request.POST) if form.is_valid(): show = form.save(commit=False) address_form_set = Address_Form_Set( request.POST, instance=Show) if address_form_set.is_valid(): show.save() address_form_set.save() return HttpResponseRedirect(reverse('show created')) else: form = Submit_Event_Form() show_formset = Address_Form_Set(instance=Address()) return render_to_response( "website/event_add_view.html", { "form": … -
'TypeError: 'DotMap' object is not callable' error at django model class
Has to be something obvious, but I can't figure it out. I am trying to define class field of type DotMap in django's model class: class SomeModel(models.Model): temp = { 'key': 'value' } dot_map = DotMap(temp) But I keep getting 'TypeError: 'DotMap' object is not callable' from 'python manage.py runserver'. I have from dotmap import DotMap at the start of the file. Would appreciate any ideas on what might cause it or how to fix it? -
DJANGO upload images dont show the django form
I have a simple auth app in Django and now I want the authentication users to can upload easy multiple files from page on website. i have create a multiupload Django form and views and html form i am not sure if my code is perfect first time play with auth but not work anyway. in the html page don't show me the form for upload show only the submit button and do nothing that. button model.py class MyModel(models.Model): user = models.ForeignKey(User, unique=True) upload = models.ImageField(upload_to='upload') views.py @login_required def upload_images(request): uploadimages = UploadImagesForm(request.POST or None, request.FILES or None) if uploadimages.is_valid(): # Get the images that have been browsed if request.FILES.get('multipleimages', None): images = request.FILES.getlist('multipleimages') for image in images: MyModel.objects.create(user=request.user.id, images=image) else: pass else: raise Http404 return render(request, 'home.html', {'UploadImagesForm':UploadImagesForm }) forms.py class UploadImagesForm(forms.Form): multipleimages = forms.ImageField(label="Upload Multiple Images:",widget=forms.ClearableFileInput(attrs={'multiple': True}), required=False) html {% extends 'base.html' %} {% block content %} <div class="container"> <div class="row"> <div class="jumbotron"> <h1>Hello</h1> <p><form class="" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ UploadImagesForm }} <input type="submit" name="" value="Submit"> </form></p> <img src="static/css/me.jpg" width="777px" height="555px";alt="some image"/> </div> </div> </div> {% endblock %} -
How can I unwrap an array from JSON file with python?
I have the following JSON: {u'messagetype': u'writefft', u'fftData': [[0, 1, 2, 1, 2, 4, 1, 0]]} How can I unwrap this so I can print each data of the array 'fftData'? Tried: data = json.loads(request.body) fftData = (data["fftData"]) print (data["fftData"]) But I doesn't achiev what I need... What this prints: [[0, 1, 2, 1, 2, 4, 1, 0]] What I want to print: 0, 1, 2, 1, 2, 4, 1, 0 Tried: print (fftData[0]) Put it prints:[0, 1, 2, 1, 2, 4, 1, 0] Can someone help me? -
Handling POST values Datatables with Django
Use Datatables plugin with Django 1.10. Process the data on the server side via POST. My problem is in capturing all the variables order[x], order[x][dir] and order[x][column] to be included in the queryset, in the POST comes the information more or less like this: draw:1 columns[0][data]:chb_chcl_id columns[0][name]: columns[0][searchable]:false columns[0][orderable]:false columns[0][search][value]: columns[0][search][regex]:false columns[1][data]:chcl_num_cheque columns[1][name]: columns[1][searchable]:true columns[1][orderable]:true columns[1][search][value]: columns[1][search][regex]:false columns[2][data]:empr_nombre columns[2][name]: columns[2][searchable]:true columns[2][orderable]:true columns[2][search][value]: columns[2][search][regex]:false columns[3][data]:cuen_nombre columns[3][name]: columns[3][searchable]:true columns[3][orderable]:true columns[3][search][value]: columns[3][search][regex]:false order[0][column]:5 order[0][dir]:asc order[1][column]:6 order[1][dir]:asc start:0 length:5 search[value]: search[regex]:false But the user can change the columns for the order of the data, so the order [] variables could be more or less, depending on the user's choice. How can I go through all the order [] variables, I have int with request.POST.getlist ('order'), request.POST.getlist ('order') -
django: one user per application while still having admin users
Be patient as I am not native english speaker and I am moving to django from PHP. This is my first django app for a book store. Currently, the default django CMS is working fine but I want to separate the project into three applications: registrar (who add books), finance (who track bulk sale of books) and the admin who will manage the project such as users. I want to keep the default user manager as it is but differentiate users based on their type. So for e.g. registrar would be sent to registrar view while finance user will be sent to finance view. Is that possible without touching the users table to add user_type or something? Or better yet, can I add permission based on application (like user registrar for the registrar application). -
docker-compose error on the welcome page
When I visit the address http://192.168.99.100:8000/ I can't see the django's welcome page in my browser. gmondesi@MRT-3-011 MINGW64 ~/Documents/GitHub/docker-django-tutorial (master) $ docker-machine ls NAME ACTIVE DRIVER STATE URL SWARM DO CKER ERRORS default * virtualbox Running tcp://192.168.99.100:2376 v1 7.04.0-ce gmondesi@MRT-3-011 MINGW64 ~/Documents/GitHub/docker-django-tutorial (master) $ docker-machine ip 192.168.99.100 gmondesi@MRT-3-011 MINGW64 ~/Documents/GitHub/docker-django-tutorial (master) $ docker-compose run web time="2017-04-09T18:03:29-04:00" level=info msg="Unable to use system certificat e pool: crypto/x509: system root pool is not available on Windows" Performing system checks... System check identified no issues (0 silenced). You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. April 09, 2017 - 22:03:31 Django version 1.11, using settings 'composeexample.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. is there another way (or localhost link) that I can access my django's welcome page? -
Django - how to run methods by dropdown select?
Is in Django forms, possible to run specific methods by selecting dropdownmenu, or radioselect? for example, when i select Input option, then run foo method and when i select Outout, run bar or so... STATUS = ( ("in", _("Input")), ("out", _("Output")), ) class MaterialFlow(models.Model): status = models.CharField(max_length=3, choices = STATUS) -
How can I upload/import a file from a list of files from a view that displays files from my media root?
I have a django app that creates a csv and stores it in the media root. In order for the user to do anything with it, they need to upload it manually to another app within the same project. I can get a list of files that are in the media root. How can I select one of those files (checkbox) and then pass it to the site for upload? -
Django objects.all() doesn`t display any content
Hi everybody! Im just starting a way of django programming so sometimes really get confused. I`m trying to display all my objects from DB, but when opening the page its simply empty. There are content added and I tried ListView previously and it worked for me. But now I need to dislpay objects like a grid and here is an issue with this method. Will be very thanksfull for any help! models.py from django.db import models class Post(models.Model): title = models.CharField(max_length=140) body = models.TextField() date = models.DateField() image = models.ImageField(upload_to='bons_images/%Y/%m/%d') def __str__(self): return self.title views.py from django.shortcuts import render, render_to_response from django.template import RequestContext from django.views import generic from blog.models import Post def image(request): post = Post() variables = RequestContext(request, { 'post': post }) return render_to_response('blog/post.html', variables) # class IndexView(generic.ListView): # template_name = 'blog/blog.html' # context_object_name = 'all_posts' # # def get_queryset(self): # return Post.objects.all() def index(request): posts = Post.objects.all() return render(request, 'blog/blog.html', {'posts': posts}) urls.py from django.conf.urls import url, include from django.views.generic import ListView, DetailView from blog.models import Post from blog import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<pk>\d+)$', DetailView.as_view(model=Post, template_name='blog/post.html')), ] blog.html {% extends 'base.html' %} {% block content %} {% if all_posts %} {% for post … -
How to upload an image from URL
I've got 2 ways to upload an image. 1 is choosing an image from the user's files and the other is for uploading an image via URL. models class Post(models.Model): ... image = models.FileField(null=True, blank=True) imageURL = models.URLField(null=True, blank=True) html <input id="id_image" type="file" name="image" /> <!--upload from file--> {{ form_post.imageURL|placeholder:"URL" }} <!--url upload--> The image upload from files works fine, the user just clicks on the input and it chooses their file. However when the user decides to use the URL option instead..how do I get that URL string and make it the value for the image field? -
generic.Listview does not show in URL list in DRF Viewer
I'm missing something, but I don't know what it is. When I go to the DRF Viewer, alerts is not listed in the possible list of urls. all the other Rest URLs do. here's my serializer.py: class OptionSerializer(serializers.ModelSerializer): class Meta: model = Options fields = '__all__' validators = [ UniqueTogetherValidator( queryset=Options.objects.all(), fields=('Member', 'skey', 'Time_Period') ) ] api.py: class OptionViewSet(generics.ListCreateAPIView): serializer_class = OptionSerializer def get_queryset(self): """ This view should return a list of all the options for the currently authenticated user. """ user = self.request.user return Options.objects.filter(Member=user) and my urls.py: router = routers.DefaultRouter() router.register(r'users', api.UserViewSet) router.register(r'groups', api.GroupViewSet) router.register(r'currency', api.BitCoinViewSet) router.register(r'latest_prices', api.CurrencyLatestViewSet) router.register(r'options', api.OptionViewSet.as_view, 'alerts') urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] Why does the alert url not show up? Thanks.