Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't see the migrate list in Django
I am working on my first Django Project and while learning about migrations I was to use this command to see the lists. python3 manage.py migrate --list But instead of giving me the list it gives an error usage: manage.py migrate [-h] [--version] [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--noinput] [--database DATABASE] [--fake] [--fake-initial] [--run-syncdb] [app_label] [migration_name] manage.py migrate: error: unrecognized arguments: --list But even after that, When I am trying to migrate usinng this commannd python3 manage.py migrate it gives no error. The only issue arises when I am trying to use the list command.So any advice will be much helpful for me.Thanks. P.S. I am using Python 3.5.2 -
Having trouble returning a User object with Django
I've been trying to use Django's authentication system to login in a user. But I can't figure out how to create a User object, I've just been playing around with it so far: def sign_in(request): form = NameForm(request.POST) if form.is_valid(): post = form.save() post.save() username = request.POST.get(post.question_text) password = request.POST.get(post.id_text) user = authenticate(username=username, password=password) if user is not None: login(request,user) return HttpResponse('hi') else: return HttpResponse('bye') else: form = NameForm() return render(request, 'checkin/sign_in_new.html', {'form': form}) The program keeps returning bye. I'm not sure what I need to put as the parameters for `request.POST.get(), the Django docs uses 'username' and 'password' respectively. Do I need to write code to create the user first? I created one in the Django API -
do I have to startapp ? app.urls not loading in project.urls.py
do I have to use the startapp command in django to create new apps? I created folders (same level as projectname/projectname directory) to store what I need (i.e. files such asprojectname/app/urls.py), instead of actually using startapp(as I had these already). But Django doesn't seem to be loading these. projectname/projectname/urls.py extract: urlpatterns = [url(r'^app/', include('app.urls', namespace='app')),] when I run makemigrations(migrating per models in all apps), Django complains(excerpt): File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/projectname/projectname/urls.py", line 8, in <module> url(r'^app/', include('app.urls', namespace='app')), File "/usr/local/lib/python2.7/dist-packages/django/conf/urls/__init__.py", line 50, in include urlconf_module = import_module(urlconf_module) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named urls Looks like Django can't find app.urls here, rite? ... any hints on what I might be doing wrong? I hope I haven't snipped out too much off my error messages! -
How do I put a python program into a django website
I made a simple program with python27. I also clumsily made a website using django framework following a youtube practice(which I did't fully understand) Now i'm trying to make my python27 program run on my django website. Is it possible to just almost copy paste my python program into view.py or 'model.py'and use it, or do I have to program again with html ? Sorry, but I can't show you an example of my program because of patent problems. Just to say my program includes 1 dictionary. You can think of it as a calculator. If you need more information, I will tell you additionally. -
Self reference ForeignKey with comment/comment reply relationship
I'm trying to implement replies to my comments and am not sure how self ForeignKey's work. Here's my Comment model. class Comment(models.Model): user = models.ForeignKey(User, blank=True, null=True) destination = models.CharField(default='1', max_length=12, blank=True) parent_id = models.IntegerField(default=0) reply = models.ForeignKey('self', blank=True, null=True) comment_text = models.TextField(max_length=350, blank=True, null=True) def __str__(self): return str(self.comment_text) Right now this is how my initial comment (parent comment) view looks like: def user_comment(request): if request.is_ajax(): comment = CommentForm(request.POST or None) ajax_comment = request.POST.get('text') id = request.POST.get('id') if comment.is_valid(): comment = Comment.objects.create(comment_text=ajax_comment, destination=id, user=request.user) comment.save() username = str(request.user) return JsonResponse({'text': ajax_comment, 'username': username, 'id': comment.id}) so that just creates a regular instance of Comment. Now here's my attempt at a reply comment (seperate view): def comment_reply(request): if request.is_ajax(): comment = CommentForm(request.POST or None) reply_text = request.POST.get('reply_text') id = request.POST.get('id') parent_id = request.POST.get('parent_id') parent = Comment.objects.get(id=parent_id) if comment.is_valid(): comment = Comment.objects.create(comment_text=reply_text, destination=id, user=request.user, parent_id=parent_id, reply=parent) comment.save() username = str(request.user) return JsonResponse({'reply_text': reply_text, 'username': username}) is reply=parent the right way to create the reply Comment object? I'm struggling with how to connect the two. My template, which just renders parent comments looks like this: {% for i in comment_list %} <div class='comment_div' data-comment_id="{{ i.id }}"> <div class="left_comment_div"> <div class="username_and_votes"> <h3><a class='username_foreign'>{{ i.user … -
Trying to get input value through ajax with Django
I'm trying to get the input value through with django using ajax is not working I hope you can help me I have seen the code all the day and I do not find the error. It suppose to give the value by an alert window. views.py def form(request): return render_to_response('prueba2.html') from django.views.decorators.csrf import csrf_exempt @csrf_exempt def form_ajax(request): if request.is_ajax() and request.method == 'POST': nombre = request.POST['nombre'] return HttpResponse(nombre) file.html <!DOCTYPE html> <html> <head> <title></title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> </head> <body> <script type="text/javascript"> $(function() { $(document).on('submit', '#fomulario', function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'http://127.0.0.1:8000/form_ajax/', async: 'true', data: $('#nombre').val(), success: function(data) { alert(data) }, }); }) }); </script> </body> <form id="fomulario"> <label for="Nombre">Nombre</label> <input type="text" name="nombre" id="nombre" value="hola"> <input type="submit"> </form> <div id="valor"></div> </html> All suppose to work properly if I make something like this: views.py def form(request): return render_to_response('prueba2.html') from django.views.decorators.csrf import csrf_exempt @csrf_exempt def form_ajax(request): if request.is_ajax() and request.method == 'POST': #nombre = request.POST['nombre'] return HttpResponse('HELLO THIS IS ME...') I think django is not taking the value of the input name. Do you have any idea how to solve this problem ? -
Wagtail returns Internal Server Error - 500 on all image and document uploads
Wagtail CMS is returning a Internal Server Error - 500 error on all image and/or document uploads, yet still uploading the files. I am using Django==1.10.5, Pillow==3.4.2 and wagtail==1.8.1. Any ideas what could be causing the error but still allow uploads? Thank you. -
QuerySet is not JSON Serializable Django
newbie programming here. I have a model with many rows and I would like to pass each row to javascript. First attempt: Views.py events = Events.objects.filter(user_id=user_id) // filter by user_id context = { "email": request.user.email, "login": True, "objects": events, } return render(request, 'fullcalendar/index.html', context) Events is the name of the table and I stored each row in events. Passed that into a dict called context which is then passed to my template. Then from my template I was able to do something like this: {% for object in objects %} <p>event.column_name</p> {% endfor %} and that would work fine, however I can't do that in the javascript section. {% for object in objects %} var date = object.date // assuming object has a column named date {% endfor %} Second Attempt So I did some research and decided to use json. In Views.py I made the following change: return render(request, 'fullcalendar/index.html', {"obj_as_json": simplejson.dumps(context)}) and from this I hoped to do this: var objects = {{ obj_as_json }} for object in objects //Do some stuff But I got the error QuerySet is not JSON Serializable Django. So I looked up how to serialize objects and made the following change: data = … -
Contact Form Error - object has no attribute 'status_code'
I am using WagtailCMS, but like to roll my own forms outside of Wagtail. I have a Contact form that I use all the time with no issues, but I am getting an object has no attribute 'status_code' upon form submission. In the traceback shown below, it references Wagtail, but I am calling the contact_page url before the Wagtail urls. I am not sure how to troubleshoot this and was hoping someone could enlighten me. Thank you. view def contact_form(request): if request.method == "POST": form = ContactForm(data=request.POST) if form.is_valid(): first_name = request.POST.get('first_name', '') last_name = request.POST.get('last_name', '') primary_phone_number = request.POST.get('primary_phone_number', '') alternative_phone_number = request.POST.get('alternative_phone_number', '') email_address = request.POST.get('email_address', '') date = request.POST.get('date', '') type = request.POST.get('type', '') interest = request.POST.get('interest', '') referred = request.POST.get('referred', '') message_content = request.POST.get('message_content', '') subject = 'New Message from Contact Form' from_email = settings.DEFAULT_FROM_EMAIL admin_email = ['charles@studiorooster.com'] recipient_list = ['charles@studiorooster.com', 'info@mylittlecarnival.com', 'omar@mylittlecarnival.com', 'lorena@mylittlecarnival.com'] ctx = { 'subject': subject, 'first_name': first_name, 'last_name': last_name, 'primary_phone_number': primary_phone_number, 'alternative_phone_number': alternative_phone_number, 'email_address': email_address, 'date': date, 'type': type, 'interest': interest, 'referred': referred, 'message_content': message_content } message = get_template('home/email_forms/contact_form_email.html').render(Context(ctx)) msg = EmailMessage(subject, message, from_email=from_email, to=recipient_list, bcc=admin_email) msg.content_subtype = 'html' msg.send() if form.errors: json_data = json.dumps(form.errors) return HttpResponseBadRequest(json_data, content_type='application/json') else: raise Http404 return … -
how part queryset in Temokate
Got code on pythom 2.7 user Django how i can parse dishs_list intemplate? userorder = UserOrder.objects.filter(user_id=self.request.user.id, is_closed=0) dishs = UserOrderItem.objects.filter( order_id=userorder[0].id).values('dish_id') \ .annotate(count=Count('dish_id')) dishs_list = list() for d in dishs: dish = Dish.objects.filter(id=d['dish_id']) shop = Shop.objects.filter(id=dish[0].shop_id) dishs_list.append([d, {dish}, {shop}]) -
Django Forms and Authentication with Front-end Framework (AngularJS/ReactJS)
Been reading and watching quite a bit about integration ReactJS into a Django project. I get the basic concepts of data flowing from Django in the form of JSON via Django REST Framework. Where tutorials seem to end though is how data flows in the reverse direction and what role, if any do Django forms play? I am thinking input elements are rendered back into JSON and then sent back through Django REST Framework in the form of PUT, PATCH, POST, etc. to update models. However, when it comes to using user input against Django's built in auth views, I am a bit lost. Does anyone have experience with this that cares to explain? -
null value in column "user_id" violates not-null constraint Django
I know there are a lot of solutions for this problem but they seem a bit different than mine. Here is my models.py: from __future__ import unicode_literals from django.db import models from django.conf import settings from django.contrib.auth.models import User from django.contrib.postgres.fields import HStoreField # Create your models here. class Events(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) name = models.CharField(max_length=32) start = models.CharField(max_length=32) end = models.CharField(max_length=32) Very simple table and I want the primary key in Auth_user to be the foreign key in my Events table. So of course this would mean that a User has to be logged in and authenticated for this to work. In my views.py I have: def createEvent(request): if request.method == "POST": user = request.user print (user) # Check for Authentication name = request.POST['name'] start = request.POST['start'] end = request.POST['end'] Events.objects.create( name = name, start = start, end =end, ) The print statement will print out the current user logged in. I can confirm that this part does show that a user is logged in and that this user is in the auth_user table with a unique id. However, when I try to submit a form, I get a null value for the user column. Any ideas? -
Django template tag within a tag for controlling HTML layout
I have an Indicator model whose view will always have descriptive text with images in variable locations. The layout of the text and images is unknown in both the template and the view. I'd like to control that in the model. Think of it like a blog post in WordPress. Each new post is a blog with a similar look and feel, but the number of images and their locations is always different. Upload a media file, then point to the image in the post. Here's my failed attempt. In the view, I'm setting context['content'] = '<p>I hope that you see an image after this.</p>' In the template, I could render 'I hope that you see an image after this' with content.as_p, but I want to serve static images inside of the content. The static image is hosted within the Django app. My attempt at forcing this is context['content'] = '<p>I hope that you see an image after this.</p>{% load static %}<img src="{% static "my_app/example.jpg" %}" alt="My image"/>' but all I see is the attempted Django template code. I reviewed many potentially duplicate posts here (I can't hard code it into the template because I don't know where the image … -
Django extract value from dict response
I have a model "Drug" that has a child foreign key "Accounting Entry" that contains a quantity. There are multiple Accounting Entries per drug and I have aggregated the sum of the child quantities to Drug as sumQuantities. The problem I have now is that when I'm rendering the template I see the following: Quantity on Hand {'Quantity__sum': 11} {'Quantity__sum': 99} {'Quantity__sum': 222} I'm trying to get the 'Quantity__sum': 11 to display as the basic value (11) but can't seem to get it to function correctly Thanks very much for any help models.py class Drug(models.Model): Facility = models.ForeignKey(Facility, on_delete=models.CASCADE) Name = models.TextField(max_length=120,default='default') def _get_sum_quantity(self): return self.quantities.aggregate(Sum('Quantity')) sumQuantity = property(_get_sum_quantity) def __str__(self): drug_name = self.Name return drug_name class Meta: verbose_name_plural = 'Drugs' class AccountingEntry(models.Model): Drug = models.ForeignKey(Drug, on_delete=models.CASCADE, related_name='quantities') Quantity = models.IntegerField(default='0') views.py def update(request): context = locals() template = 'update.html' return render(request, 'update.html', {'drug_list': Drug.objects.all()}) HTML Snippet {% for drug in drug_list %} <td>{{ drug.Name }}</td> <td>{{ drug.sumQuantity }}</td> {% if not forloop.last %} </tr> <tr> {% endif %} {% endfor %} -
Django Filter QuerySet on List Using AND
I'm trying to user Django's .filter() method with a list of related child objects to return the parent object set that contains all of the child records. See example below. User is the parent object and Color is the child object directly related to User User1 has colors [red, blue] User2 has colors [black, purple, green, blue] User3 has colors [red, blue, green] User4 has colors [red, blue, green, white] users = users.filter(user_colors__color__in=colors) colors is a list set by the POST. E.g. [red, blue, green] Currently, users contains the set of users which have any of [red, blue, green]. For the sample set above, I am currently getting User1, User2, User3 and User4 with the code above. I.e. it's using an OR search. I want to return only the users which have ALL of the specified colors. I.e. use an AND search. For the example above, I want to only get User3 and User4. What is the best way to get only the set of parent records (users) that have all of the requested child records (colors)? Is there a Django method that can do this easily? Or do I need to a loop that filters on each color? Thanks! -
Method for adding sub-section to an inline admin in Django?
So like the title says. I am building a book structure and I am looking to make it so when in the admin panel and editing a book object, one can view and add related pages to the book. The page itself also has related objects called sections that are essentially paragraph objects within the page object. My model is below: class Textbook(models.Model): founder = models.CharField(max_length=256) title = models.CharField(max_length=256) cover = models.ImageField(upload_to=get_image_path, blank=True, null=True) def __str__(self): return self.title class Page(models.Model): textbook = models.ForeignKey(Textbook,related_name="pages") page_title = models.CharField(max_length = 256) page_num = models.IntegerField() def __str__(self): return self.page_title class Section(models.Model): page = models.ForeignKey(Page,related_name="sections") section_title = models.CharField(max_length=256) text = models.TextField(max_length = 1024) image = models.CharField(max_length = 256) def __str__(self): return self.section_title Ideally there would be an add new page button within the textbook add/edit panel where I could then add section to that previously mentioned page. Current admin.py: class PageInline(admin.TabularInline): model = Page class TextbookAdmin(admin.ModelAdmin): inlines = [ PageInline, ] admin.site.register(Textbook,TextbookAdmin) admin.site.register(Section) Is there a currently built in method like a nest inline that could be used or I am just not thinking in the right mindset for Django? If this is not the proper or ideal way to structure this, what is the … -
How to reach form.serialize() data from Ajax call in Django views
I have this ajax piece of code: data: form.serialize(), How to use it in Django view? I know how to get basic input values: request.POST['example'] But how to deal with forms? -
Python Validate to only allow Numbers and 2 Decimals
was wondering if anyone could help me to validate my entries to only allow numeric values with two decimal places. Here is the models.py class Records(models.Model): capital = models.DecimalField(max_digits=10, decimal_places=2) years = models.DecimalField(max_digits=10, decimal_places=2) rate = models.DecimalField(max_digits=10, decimal_places=2) amount = models.DecimalField(max_digits=10, decimal_places=2) -
Advice on making a threaded comment system in Django
I'm in the middle of making my Django commenting system. What i've done so far is: AJAX initial comments (parent comment appended without page refresh/saved to database) Django initial comments (able to render the parent comments above after page refresh) AJAX 1st reply (1st reply appended without page refresh/saved to database) Now this is where i'm up to. As I want to have a threaded (endless) comment system where users can continuously reply to each other, I want to have a clear outlook of how I will do this before I start. My Comment model looks like this: class Comment(models.Model): user = models.ForeignKey(User, blank=True, null=True) destination = models.CharField(default='1', max_length=12, blank=True) parent_id = models.IntegerField(default=0) comment_text = models.TextField(max_length=350, blank=True, null=True) def __str__(self): return self.comment_text My AJAX call looks like this: var str = window.location.href.split('?')[0]; var path = str.split("/")[4]; $('.comment_form').on('submit', function(e) { e.preventDefault(); var c = $(this).find('.comment_text').val() $.ajax({ type: 'POST', url: '/user_comment/', data: { text: $(this).find('.comment_text').val(), id: path, csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val(), }, success: function(data) { $('.commentsContainer hr').prepend("<div class='comment_div'><div class='left_comment_div'>" + <h3><a href='#' class='username'>" + data.username + "</a></h3><p>" + data.text + "</p><a href='#'><span class='comment_delete'>x</span></a></div>"); } }); }); comments template <div class="commentsContainer"> <form action="" class="comment_form">{% csrf_token %} {{ comment.comment_text|add_class:"comment_text" }} {{ comment.id }} <input type="submit" value="Comment" … -
Django compare passed in value to a variable on the fly
I have the following in my template inside of a table: {% for sb in ship_back %} <tr> <td>{{ sb.ring_name }}</td> <td>{{ sb.release.ring }} pp{{ sb.release.ppack }}</td> </tr> {% endfor %} This produces the following output: Larry 15 pp28 Moe 15 pp29 Curly 15 pp30 Shemp 16 pp7 I would like to add a horizontal line in the table whenever the {{ sb.release.ring }} value changes. In the above example, that would come in between Curly and Shemp. I would normally create a variable for this outside the for loop, set it's initial value to 0, make a comparison at the beginning of the for loop (ignoring the 0 case) and if it did not match the current value of {{ sb.release.ring }}, I would insert the horizontal line. I'm struggling to figure out how to accomplish this in Django. -
Django-Executing Python code in HTML
I have a python script written up that returns a list of values from a database. I want to incorporate that script into my django website that I have created. I have an html file right now in my templates folder that has dictionary values hardcoded but how do I replace the dictionary hardcoded material with the script, lets call it values.py <script type="text/javascript"> $(document).ready(function() { var dropDown = [" ", "Run1", "Run2", "Trail1", "Trail2"]; var dropDownID = [" ", "111111", "222222", "333333", "444444", "555555"]; $("#dropDown").select2({ data: dropDown }); $("#dropDown").change(function() { $("#dropdownID").val(dropDownID[$("#dropDown option:selected").index()]); }); }); -
Can heroku be used as a production server?
Can heroku be used as a production server for high-traffic django web apps/sites? Is it possible that it might be beneficial to use a VPS on the other hand? -
Django: Generate list of strings
I have a function that I pass to the context in views.py and use in a django template for use in a javascript chart. function: def cleaning_data_plotly(area_id): _input = pricecleaning.values('percent_of_obs','price_cleaning',) data = [] for row in _input: data.append(str("Price of cleaning is " + str(row['price_cleaning']) + " USD in " + str(percent_of_obs)+" % of cases")) return data template: text: {{ price_cleaning }}, When I inspect the output I see this: text: [&#39;Price of cleaning is 68 USD in 3.58 % of cases &#39;, &#39;Price of cleaning is 78 USD in 7.58 % of cases &#39;], Whereas I expected this: text: ["Price of cleaning is 68 USD in 3.58 % of cases", "Price of cleaning is 78 USD in 7.58 % of cases"], How do I get proper strings? Any help is much appreciated! I'm using Python 3.5 and Django 1.10. -
DJANGO images(upload/download)
who is the better method to take images from uses(visitors)on the fly on my web site and to return the new images(with some processing) back to users using DJANGO? i am new i dont know how to connect my python script with the html templates to take the images and how to return. for example my script take images paths to processing new images with new paths. a simple image classification with GDAL : # Input file name (thermal image) src = "thermal.tif" # Output file name tgt = "classified.jpg" # Load the image into numpy using gdal srcArr = gdalnumeric.LoadFile(src) # Split the histogram into 20 bins as our classes classes = gdalnumeric.numpy.histogram(srcArr, bins=20)[1] # Color look-up table (LUT) - must be len(classes)+1. # Specified as R,G,B tuples lut = [[255,0,0],[191,48,48],[166,0,0],[255,64,64], [255,115,115],[255,116,0],[191,113,48],[255,178,115], [0,153,153],[29,115,115],[0,99,99],[166,75,0], [0,204,0],[51,204,204],[255,150,64],[92,204,204],[38,153,38], \ [0,133,0],[57,230,57],[103,230,103],[184,138,0]] # Starting value for classification start = 1 # Set up the RGB color JPEG output image rgb = gdalnumeric.numpy.zeros((3, srcArr.shape[0], srcArr.shape[1],), gdalnumeric.numpy.float32) # Process all classes and assign colors for i in range(len(classes)): mask = gdalnumeric.numpy.logical_and(start <= \ srcArr, srcArr <= classes[i]) for j in range(len(lut[i])): rgb[j] = gdalnumeric.numpy.choose(mask, (rgb[j], \ lut[i][j])) start = classes[i]+1 # Save the image gdalnumeric.SaveArray(rgb.astype(gdalnumeric.numpy.uint8), \ tgt, … -
Django: Get all objects and the first record of a related model
Initially I was just grabbing all camera models: cameras = Camera.objects.all() But I now need to also include the latest record of CameraLog for each Camera that is called in the statement above. CameraLog has a foreign key for the Camera it's associated with. I'm pretty new to Python, so I'm sure this is an easy modification for you guys... cameras = Camera.objects.all( and also the latest CameraLog )