Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why uses South to do migration in Django?
I am maintaining a Django project in version 1.6.X. I had found some doubt and issue a question here. As my known, Django from version 1.7 is able to do migration. And, I started to get Django it is version 1.7. Its built-in scripts have migration. Therefore, I have no experience about doing migration by South. So, I have a question. When Django hasn't migration before 1.7, the Django project adopt South as migration solution. Right? If I update the Django project to version 1.7.x, may I deprecate South? -
How can I do to show a link in a template only for an amdinistrator?
I have a template called index.html. Also I have a link in the index.html called admin. I need to show the link admin only for an administrator, in other words only for me. How can I do it? -
Django - not replacing my string as expected
I need help I have no clue how to solve it. I'm working with files. Basically I'm opening a file, reading what's inside it, look for a word and replace the word next to it I'm opening a text file, in this case I have two words which are called with the same name, they are separated for PART 1 and PART 2 this is my car.txt PART 1 car toyota PART 2 car toyota as you can see I have the same word separated for part so my script will look for both and show this in my template.. this is how it's working views.py def car_p1(): file = open("car.txt","r") content = file.read() file.close() car = re.findall('car\s(.*?)\s',open('car.txt','r').read()) if car: print car else: print 'no car found!' return car[0] def car_p2(): file = open("car.txt","r") content = file.read() file.close() car = re.findall('car\s(.*?)\s',open('car.txt','r').read()) if car: print car else: print 'no car found!' return car[1] def get_items(request): car = car_p1() car2 = car_p2() if 'car' in request.POST: car_change(request) return redirect('get_items') return render(request, 'cars.html', {'car':car, 'car2':car2,}) def car_change(request): car = car_p1() car2 = car_p2() if request.method == 'POST': change_car = str(request.POST['car_1']) change_car_2 = str(request.POST['car_2']) filedata= None with open('car.txt', 'r') as f: filedata = f.read() β¦ -
How do I get the first name and last name of a logged in user in Django?
I need to get the first name and last name of a user for a function in my views How do I do that? What is the syntax for it? I used request.user.email for the email, but I don't know see an option for a first name or last name. How do I go about doing this? Should I import the model into the views and then use it? -
Can I modify the sql query generated by values() before it gets executed in django
I wanna modify the queries generated by django before it gets executed in database, is it possible? Thanks! -
Using the slice filter with context data from a Django QuerySet
I am trying to split a list from my model across two columns, using this html code in the template: < div class ="col-md-6" > {%for value in object_list %} <ul>< ahref="/sites/{{value.url}}/">{{value.Site}}</a></ul> {% endfor %} I was planning to achieve this with the slice tag to filter the list, e.g.: {%for value in object_list|slice:"10:20" %} It does not work however, and I think it might be because I have context data i.e. {{value.Site}}, instead of just {{Site}} for example. This is the corresponding view: class homeview(ListView): template_name = 'annual_means/home.html' def get_queryset(self): return AnnualMean.objects.values("Site", "url").distinct() What do I need to do to get the slice to work? -
Test Django admin form
I'd like to test adding a custom document file form in my application in the admin panel. Unfortunately django documentation is quite obscure about this one. This is my model: class Document(models.Model): pub_date = models.DateTimeField('date published') title = models.CharField(max_length=255) description = models.TextField() pdf_doc = models.FileField(upload_to=repo_dir, max_length=255) This is my test: from django.test import TestCase from django.test import Client from django.utils import timezone from datetime import datetime, timedelta class DocumentAdminFormTest(TestCase): def test_add_document_form(self): client = Client() change_url = 'admin/docrepo/document/add/' today = datetime.today() filepath = u'/filepath/to/some/pdf/' data = {'title': 'TEST TITLE', 'description': 'TEST DESCRIPTION', 'pub_date0': '2000-01-01', 'pub_date1': '00:00:00', 'pdf_doc': filepath, } response = client.post(change_url, data) print('REASON PHRASE: ' + response.reason_phrase) self.assertIs(response.status_code, 200) I'd like to get positive response while posting the form with shown data. For some reason response.status_code gives 404 and response.reason_phrase gives 'Not Found'. Is it possible the problem lies in the directory? -
Path to static file in Django
I'm completely lost and can't figure out how to configure path to just one css file. The site structure is: --mysite | |-/static | site.css What should I put into STATIC_URL and STATIC_ROOT? And how to link this file? (Currently it's <link rel='stylesheet' href="{% static 'site.css' %}" /> ) and STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') The error is: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/mysite/static/site.css Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: ^admin/ ^hello/$ ^mysite/$ ^static\/(?P<path>.*)$ The current URL, mysite/static/site.css, didn't match any of these. -
Disable/Modify PATCH response from django server
I am currently writing a server which will collect data from many devices throughout the field. I'm using mongodb for data storage, and I do have a EmbeddedDocumentList, 3 of them in fact. So the model for one object looks like this: { "id": ObjectID(), "gps":{ "lat": double, "lon": double } list1:[{ "id": ObjectID(), "timestamp": DateTime, "username": String, "data1": int }] list2:[{ "id": ObjectID(), "timestamp": DateTime, "username": String, "data2": int }] list3:[{ "id": ObjectID(), "timestamp": DateTime, "username": String, "data3": int }] And my goal is to update the internal lists buy values upon their arrival from devices. Also I have modified PATCH to append the value at the end of the corresponding list. However the problem I'm facing now is that after patch Django sends a response with new object which contains all data from all lists. Is it possible to disable or modify the response I'm getting? -
Can there be an else block statement in python try-except? [duplicate]
This question already has an answer here: Python try-else 19 answers I'm trying to write a subscription list module. So, I have a statement that may, depending on the email id of the user, throw an index out of range error. If it does, I want the program to do something and if it doesn't I want the program to something else entirely. How would I go about this? Currently I have code that tries to add all user irrespective and crashes the program. What I would ideally like to have is something like this: try: check_for_email_id.from_database except IndexError: create.user_id.in_database user.add.to.subscribe_list else: user.add.to.subscribe_list I need to be able to add a block here saying, if there was no IndexError, omit the "do something" part and do the else part. Does Python provide an inbuilt option for this? Can I use if-else blocks in Try-Except statements? And also, what would be a good approach to avoid writing the code for user.add.to.subscribe_list twice; other than creating a new user_add function? -
How to display in a dropdown the values of a attribute of a ForeignKey in the DJango admin interface?
I'm trying to display in Task in a dropdown the values of the name attribute of the Project. I only made it to work only as readonly a field Here is what i tryed but it's not ok. If I uncomment the line with readonly_fields it shows the name but is readonly of course(from when I had something like here How to display/use a dropdown in the django admin) in models.py I have: class Project(models.Model): name = models.CharField(max_length=200) description = models.CharField(max_length=200) def __str__(self): return '%s %s' % (self.name, self.description) class Task(models.Model): name = models.CharField(max_length=200) description = models.CharField(max_length=200) project = models.ForeignKey(Project, on_delete=models.CASCADE) def __str__(self): return '%s %s' % (self.name, self.description) and in admin.py I have: class TaskAdmin(admin.ModelAdmin): #readonly_fields = ['get_projectName2'] fieldsets = [ (None, {'fields': ['name' ]}), ('Task information', {'fields': ['description' ]}), (None, {'fields': ['get_projectName2']}), ] list_display = ('name', 'description','get_projectName2') search_fields = ['name'] def get_projectName2(self,obj): return obj.project.name get_projectName2.short_description = 'Project' Thanks! -
JS stops working on child template when I perform an AJAX call to change the queryset
My comments.html child template looks like this: <div class="commentsContainer"> {% for comment in comment_list %} ... {{ comment.text }} ... {% endfor %} </div> When I click on a button I call this AJAX function: $('.comments_new').on('click', function() { $.ajax({ type: 'GET', url: '/new_comments/', data: { }, success: function (data) { $('.commentsContainer ').replaceWith(data); } }) }); which calls this view to change the queryset (the inital queryset is comment_list = Comment.objects.filter().order_by('-score__upvotes'): def new_comments(request): if request.is_ajax(): comment_list = Comment.objects.filter().order_by('-timestamp') html = {'comment_list': render_to_string('comments.html', {'comment_list': comment_list})} return JsonResponse(html) This successfully swaps the querysets, however for some reason no javascript works on the newly loaded template/queryset. Can somebody tell me why this happens and how I can fix it? PS: it sometimes gives this error in my terminal when the call is made: UserWarning: A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext. -
How can I send a variable from swift and print it out using PHP (or Django)
Lets say I click a button in Swift and a variable is created, how can i send a POST request of the value to PHP (or Django) running on localhost. -
Resize an image in Django before upload?
How can I resize an image before uploading it in Django? I have a screen where a user can upload an image, but before they upload it, I would like to scale it to 500,500. In PIL I can easily do this locally via: from PIL import Image img = Image.open("/Users/Admin/Desktop/example.jpg") img = img.resize((750,500),Image.ANTIALIAS) img.save() How would I go about doing this in a Django view without having to upload the image first? -
crispy forms required field message localization
I'm new in Django And I'm doing my first educational project by one of the tutorial books. Here we use crispy forms to make contact-form. And there are several required fields. When I tried to submit form without these fields I get error message "Please fill out this field" . (see screeenshot). I have a question if there is easy solution to localize such messages?enter image description here -
How to manage.py loaddata in Django
I've being fighting with this command for several hours now. If I do python manage.py dumpdata --natural-foreign --> data.json when I loaddata I get the error Could not load contenttypes.ContentType(pk=19): duplicate key value violates unique constraint "django_content_type_app_label_76bd3d3b_uniq" DETAIL: Key (app_label, model)=(misuper, stockitem) already exists. Then if I do python manage.py dumpdata --natural-foreign --exclude=contenttypes --> data.json I get a similar error but with a Μ£auth.Permission object. And if I do python manage.py dumpdata --natural-foreign --exclude=contenttypes --exclude=auth --> data.json when I loaddata I get User matching query does not exist Of course, I'm excluding the auth table. So ... how does the command loaddata work! :/ I believe the docs are insufficient. -
django url include with multiple urls doesn't work
so I have this code: urls.py from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^myapp/', include('myapp.urls')), ] myapp.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^what/', views.do_something), ] going to myapp/ works but going to myapp/what doesn't work and ends up returning 404 page not found... what did I do wrong? -
Django python has stopped working when trying to run server after closing it once
python manage.py runserver works fine the first time, but after closing it with ctrl+c, I can't start it up again. I get the error message "Python has stopped working". This is easily fixed by restarting my computer but it is very inconvenient. I have also tried the same thing using pycharm, but i get the error message: Process finished with exit code -1073741819 (0xC0000005) I am currently on Windows 10. -
ProgrammingError: cannot cast type double precision to time without time zone
I have a django app with the following model: class Event(models.Model): # id = models.IntegerField(primary_key=True) event_type = models.ForeignKey( EventType, on_delete=models.DO_NOTHING, # we don't want to delete anything in the StatusType table. blank=True, null=True, ) reason_code = models.IntegerField(default=0) elapsed_time = models.IntegerField(default=0) event_at = models.DateTimeField("Event Time", blank=True, auto_now_add=True) object_id = models.ForeignKey(Machine, on_delete=models.DO_NOTHING, ) count = models.BigIntegerField(blank=True, null=True) position = models.IntegerField(blank=True, null=True) rfid_tag = models.ForeignKey(Employee, blank=True, null=True, on_delete=models.DO_NOTHING, verbose_name='User Name') hidden = models.BooleanField(default=False) # for hiding from lists # def __str__(self): # __unicode__ on Python 2 # return self.event_type class Meta: verbose_name = 'event' verbose_name_plural = 'Events' def __str__(self): return str(self.id) While trying to run a simple migration, I keep getting this error: File "/home/icar/E-Django/venv/local/lib/python2.7/site-packages/django/db/utils.py", line 95, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/epicar/E-Django/venv/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: cannot cast type double precision to time without time zone The problem I'm having with this, is I don't understand WHY it's trying to CAST the double precision to time without time zone. I don't want it to. I'm not quite sure what else to try. I have tried doing the following: ο»Ώ SELECT CAST(elapsed_time as double precision) FROM event; I also tried changing the elapsed_time field to integer and got β¦ -
Folder organization Django Rest Framework
Well it does not allow me to access the my django rest framework folder, it does not allow me to import the libraries that are needed. This example apps/ βββ apis β βββ admin.py β βββ __init__.py β βββ management β β βββ commands β β βββ __init__.py β βββ migrations β β βββ __init__.py β βββ models.py β βββ serializers.py β βββ tests.py β βββ urls.py β βββ views.py βββ bank βββ cart βββ category β βββ migrations βββ core β βββ admin.py β βββ admin.pyc β βββ apps.py β βββ __init__.py β βββ __init__.pyc β βββ migrations β β βββ 0001_initial.py β β βββ 0001_initial.pyc β β βββ 0002_auto_20170123_2008.py β β βββ 0002_auto_20170123_2008.pyc β β βββ 0003_auto_20170131_1224.py β β βββ 0003_auto_20170131_1224.pyc β β βββ __init__.py β β βββ __init__.pyc β βββ models.py β βββ models.pyc β βββ tests.py β βββ views.py βββ __init__.py βββ __init__.pyc βββ location β βββ admin.py β βββ admin.pyc β βββ apps.py β βββ __init__.py β βββ __init__.pyc β βββ migrations β β βββ 0001_initial.py β β βββ 0001_initial.pyc β β βββ 0002_delete_lakes.py β β βββ 0002_delete_lakes.pyc β β βββ __init__.py β β βββ __init__.pyc β βββ models.py β βββ models.pyc β βββ tests.py β¦ -
Django CkEditor multiple extraplugins
I am trying to add two extraplugins to CKEditor settings in Django. I found the join syntax but it does not work. If I use each of them alone, each of them works alone fine. Why don't they work together? CKEDITOR_CONFIGS = { 'forum_ckeditor': { 'toolbar': 'Custom', 'height': 300, 'width':'auto !important', 'toolbar_Custom': [ ['Bold', 'Italic', 'Underline'], ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'], ['Link', 'Unlink'], ['RemoveFormat'], ['Smiley'], ], 'extraPlugins': ','.join(['entities', 'bbcode',]), }, } -
Django Cors Headers not working for me
I have installed Django Cors Headers and I am connecting through Angular from localhost:3000 and I have my Django application running in the :8000. My enviroment is Python 2.7 I uploaded public gist and I installed corsheaders package -
Deleting related objects deletes the ForeignKey object
I have a question and answer model class Question(models.Model): description = models.CharField(max_length=255) class Answer(models.Model): text = models.CharField(max_length=255) question = models.ForeignKey(Question, related_name='answers') When I run the query below the question model is also deleted question.answers.all().delete() Is there any way to delete the answers without deleting the question? I tried iterating over the answers and that didnt work answers = question.answers.all() for answer in answers: answer.delete() I thought the queryset was lazy so maybe I needed to evaluate it before deleting so I printed it and this did not work. print answers answers.delete() I know that making the ForeignKey nullable would provide me with methods like clear and remove but I did not want to do this because I did not want any orphaned answers. -
timezone aware datetime objects in django templates
I'm having trouble understanding how to use datetime objects in a django db. I'm storing datetime.now() in a DateTimeField but having trouble displaying it in a readable way. Currently it displays UTC time. Should I storing a timezone with the datetimefield or should I always be converting it to my timezone during queries and template views? This is so complicated I must be doing this completely wrong. How would I display Pacific timezone time in a template if that were the case? Thank you. {% for session in session_list %} {{session.date}}{{session.email}}{{session.userData}} {% endfor %} -
Django ORM - Soft delete objects with flag, but still be able to look them up in related queries
We've developed quick way to do soft deletes in Django by: Adding a delete_on field to models that could be 'soft deleted' Set objects = OurObjectManger in the model OurObjectManager just overrides get_queryset and appends filter(deleted_on=None) to the queryset. Calling instance.soft_delete() sets the deleted_on field Works well in practice, Transfers are hidden when they're deleted and queries don't return them. The only problem is we'd like these still to show up when being referenced by foreign key in another model. For example the Transaction model references Transfer such as transaction.transfer, which is now None to Django. Any ideas?