Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django models - how to cancel on_delete=models.CASCADE
Trying to migrate a field from cascade to "non-cascade" seems to be ignored (Django 1.10). Previous model: class Run(models.Model): ... analysis_retention = models.ForeignKey('analysis_retention.AnalysisRetention', null=True, default=None, on_delete=models.CASCADE) New Model: class Run(models.Model): ... analysis_retention = models.ForeignKey('analysis_retention.AnalysisRetention', null=True, default=None) "manage.py makemigrations" doesn't detect the changes. Trying an explicit None doesn't help. What would be the way to remove cascading? Thanks -
Why i get "Uncaught RangeError: Maximum call stack size exceeded" in the following ajax code?
I am trying to login the user by opening the bootstrap login modal and filling it with username and password but the movement i hit 'Login' button the bootstrap modal freezes and then after few secs it displays following error message in the browser's console: And i also would like to mention that i get this error in every user's password field in django admin: html: ( bootstrap modal code ) <div id="loginmodal" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <form id="loginForm"> {% csrf_token %} <div class="modal-content" data-method="post" id="modalform" > <div class="modal-header"> <!--Heading and the closing button --> <button type="button" class="close" data-dismiss="modal">&times;</button> <h3 class="modal-title">Log In.</h3> </div> <div class="modal-body"> <div class="form-group"> <input type="text" autocomplete="off" placeholder="Email." class="form-control" id="usrnm"><br/> <input type="password" autocomplete="off" class="form-control" id="pwd" placeholder="Password."><br/> <input type="checkbox"> Remember me <br/> <a style="float: right;" href="#" data-dismiss="modal" data-toggle="modal" data-target="#signupmodal">Not a member ? </a><br/> <p style="float: left;"><a href="#"> Forgot Password?</a></p> </div> </div> <!--Closing Button in footer --> <div class="modal-footer"> <button type="submit" id="login" class="btn btn-default">Login</button> <button type="button" class="btn btn-default" data-dismiss="modal">Close </button> </div> </div> </form> </div role="modal dialog"> </div role="model of login"> ajax: $('#loginForm').on('submit',function(e){ e.preventDefault(); $.ajax({ type: "POST", url: "/librarysystem/login/", data: { 'username':username, 'password':password, csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, dataType: 'json', success: function(data){ if (data.response) { alert("Invalid"); } else alert("Valid"); … -
Puput (Wagtail based blog) - Where are the files?
I've added a puput blog to an existing Django project. I followed all the steps for setting up a standalone blog app (https://puput.readthedocs.io/en/latest/setup.html). It works fine in that I now have working blog at http://127.0.0.1:8000/blog/ and can edit the content and add new posts at http://127.0.0.1:8000/blog_admin/ . But where are all the files? Specifically the template file. I don't see any new folders or files in my Django project. I would like to edit the html template in order to get a layout that fits with my project. But I can't find any files to edit. I how someone can help. Thanks! -
Django: How can I implement Hierarchy of classes in Django?
I am completely aware of MVC Framework and how Django implements models and views. What I want to know how can I implement custom Hierarchy classes and then use them in Django. For instance: There is an abstract Class Employee and then subclasses; Permanent Employee,Interns etc. An employee can be hired and fired by the company. -
jquery ajax slider in django project
I want to make a slider in django but a simple slider with 15-20 images will take huge amount of time while loading the webpage. I want to make that slider with ajax. But I have basic knowledge of jquery with no experience in ajax. -
Django - Not a valid choice (escaped?)
I have a model with a status field that looks something like this: PENDING = 'pending' DONE = 'done' CANCELED = 'canceled' class Event: EVENT_STATUSES = [(1, PENDING), (2, DONE), (3, CANCELED)] status = models.CharField(max_length=20, choices=EVENT_STATUSES, default=PENDING) I have a serializer: class EventUpdateSerializer(serializers.ModelSerializer): class Meta: model = Event fields = ('status') And when it is called with the following JSON: { "status": "done" } I get the response: { "status": [ "\"done\" is not a valid choice." ] } Clearly (I think), the problem is the escaping of done, but why? And how do I prevent it? (I have a content-type application/json header). Thanks ahead, -
Hi I am new to Django Framework.getting error :No Module Named
Traceback: File "C:\Users\Nitin\env_mysite\lib\site-packages\django\core\handlers\base.py" in get_response 119. resolver_match = resolver.resolve(request.path_info) File "C:\Users\Nitin\env_mysite\lib\site-packages\django\core\urlresolvers.py" in resolve 365. for pattern in self.url_patterns: File "C:\Users\Nitin\env_mysite\lib\site-packages\django\core\urlresolvers.py" in url_patterns 401. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Nitin\env_mysite\lib\site-packages\django\core\urlresolvers.py" in urlconf_module 395. self._urlconf_module = import_module(self.urlconf_name) File "C:\Users\Nitin\env_mysite\lib\importlib__init__.py" in import_module 126. return _bootstrap._gcd_import(name[level:], package, level) File "C:\Users\Nitin\env_mysite\Scripts\website\website\urls.py" in 17. from website.views import hello Exception Type: ImportError at / Exception Value: No module named 'website.views' -
Djando redirecting from one view to anoter
I'm trying to redirect to a view function from another using djando redirect(). def view1(request): message="hello! redirection was done!!" return render(request,'test.html',locals()) def view2(request): return redirect(view1) but I'm getting NoReverseMatch exception. My urls.py is as shown below from django.conf.urls import url from django.contrib import admin from .views import signup,auth_test,redirected,view2 urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^signup/$' ,signup), url(r'^login/$', auth_test), url(r'^simple',view2) #url(r'^locallibrary.views.redirected/$',redirected) ] any help will be appreciated thank you error page NoReverseMatch at /simple Reverse for 'locallibrary.views.view1' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] Request Method: GET Request URL: http://127.0.0.1:8000/simple Django Version: 1.10.4 Exception Type: NoReverseMatch Exception Value: Reverse for 'locallibrary.views.view1' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] Exception Location: C:\Users\Hp\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 392 Python Executable: C:\Users\Hp\AppData\Local\Programs\Python\Python35-32\python.exe Python Version: 3.5.2 Python Path: ['C:\\Users\\Hp\\PycharmProjects\\locallibrary', 'C:\\Program Files (x86)\\JetBrains\\PyCharm 145.597.11\\helpers\\pycharm', 'C:\\Users\\Hp\\PycharmProjects\\locallibrary', 'C:\\Users\\Hp\\AppData\\Local\\Programs\\Python\\Python35-32\\python35.zip', 'C:\\Users\\Hp\\AppData\\Local\\Programs\\Python\\Python35-32\\DLLs', 'C:\\Users\\Hp\\AppData\\Local\\Programs\\Python\\Python35-32\\lib', 'C:\\Users\\Hp\\AppData\\Local\\Programs\\Python\\Python35-32', 'C:\\Users\\Hp\\AppData\\Local\\Programs\\Python\\Python35-32\\lib\\site-packages'] Server time: Sun, 5 Feb 2017 12:31:15 +0530 -
Page not found error,the way to write URL is wrong?
I got an error,Page not found (404). Error page says, Request URL: http://localhost:8000/accounts/upload_save/registration/accounts/photo.html but ^accounts/ ^upload_save/$ [name='upload_save'] is right. I can understand the meaning,but I do not know how to fix it. I wrote in urls.py(App name is accounts), from django.conf.urls import url from . import views from django.contrib.auth.views import login, logout urlpatterns = [ url(r'^photo/$', views.photo, name='photo'), url(r'^upload/(?P<p_id>\d+)/$', views.upload, name='upload'), url(r'^upload_save/$', views.upload_save, name='upload_save'), ] in views.py, def upload(request, p_id): d = { 'p_id': p_id, } return render(request, 'registration/accounts/photo.html', d) def upload_save(request): photo_id = request.POST.get("p_id", "") print(photo_id) print("hoge") if (photo_id): photo_obj = Post.objects.get(id=photo_id) else: photo_obj = Post() files = request.FILES.getlist("files[]") print(files) photo_obj.image = files[0] # photo_obj.image2 = files[1] # photo_obj.image3 = files[2] photo_obj.save() return redirect("registration/accounts/photo.html") When upload_save method is accessed,I wanna access photo.html.So,I wrote codes lilke those.Please tell me how to fix the error. -
Show previously attached file in HTML form while editing
I am writing a Django application where I have a HTML form to get a few inputs from the user. One of the inputs is an (optional) attachment file. The user is also provided with option to edit the form at some point in future. When the user chooses to edit the form, the Django view returns the ModelForm and in the template I populate all the fields. But I am not able to populate the attachment in the file input tag. However, I can see that the form object has the attachment in it. I found a few SO questions which asks for attaching a new file using scripts. And that is not possible due to security reasons. But I am looking for populating the file returned by the server on HTML page. Is there a way to populate attached files with input tags? -
Django change site language
I am using Django and I want to change the site language when users click a button for example. I can get the current language code using {% get_current_language as LANGUAGE_CODE %} but how can I change it from a template? -
Learning Python the best way
So I just got a couple of questions regarding learning Python. I just started learning ruby/rails couple of months back and got a part-time job on a company that uses the framework. Now I will like to add something useful to my toolbox, and I decided to learn Python as it seems to be the best option. Now I will like to know in your opinion what would be the best way to learn it, in a way that if a new framework or technology that uses Python comes around, will be more easy for me to jump into. I was thinking on using Django and build some projects like blogs or simple e-commerce app's. I'm not sure if that would be the best option. Sorry for the bad English! -
Django Doc Convert to PDF
I am looking for a pdf converter which allows me to convert doc to pdf in my Django (1.10) project. Specifically, I am using docx to generate a document in django and push to download. One step further, I would like to convert the document into pdf for pushing to download, however not creating any temp file on the server. The workflow would be like this: Django db content -> document of docx > pdf converter > python BytesIO > HttpResponse as pdf attachment I have looked up for ReportLab and wkhtmltopdf, but they are all building pdf from html or scratch with massive formatting that have to be handled. I am just looking for a simple one like MsOffice can save working doc into pdf format. Any idea of approach that can be recommended? Thanks a lot. -
Django REST Framework and Serializing Lists of Objects
I am using Django REST Framework. My viewsets are subclassed from ModelViewSet and my sterilizers are subclasses from ModelSerializer. I wish to support serializing a list of object so users are able to POST multiple objects at once. This is supposed to be quite straightforward, with passing many=True when instantiating the serializer. he problem is I do not instantiate the serializer my self. Instead, the ModelViewSet class simply requires a serializer_class field to be given. So, ow can I add support for serializing lists while using ModelViewSet and ModelSerializer? -
ModelForm.is_valid() is False when row already exists. How to get the object?
My Location model has a unique filed called name. Through LocationForm I get user input and try to either insert it into the database or get the axisting object. But if user inputs an existing name, lf.is_valid() becomes False and I never get to the get_or_create command. Any idea how I can pass this? lf = LocationForm(request.POST or None) if lf.is_valid(): location_instance, created = Location.objects.get_or_create(**lf.cleaned_data) Thanks, -
Django Rest Framewrok Get Forms as json
Django Rest Framework is populating the HTML form.Like This Is any way possible can get the html form in json format as well along with default behaviour. In case of this attached image something like { "first_name":{"type":"text"}, "last_name":{"type":"text"}, } -
How to add class to widget/field with Django 1.11 template-based form rendering
Note: This question shouldn't be conflated with past questions that are similar but before Django 1.11, when they released template-based form rendering. I understand that Django now has template-based form rendering. From what I understand, this is supposed to fix the issue of having to inject classes from the view or the form, rather than keeping all of the HTML/CSS in the templates. So, my questions are: How do I add a class (for example, form-text) to all TextInput widgets from the template system? How do I add a class (for example, alert-warning) to all error messages (validation failures) from the template system? I may have misunderstood something about this new feature, so if I did, feel free to let me know if this isn't how it works or if I am asking the impossible. Ideally, I would like to implement these form rendering changes to the master template. -
What is the return type of clean_formField of manytomany field in django? Can I return list from the function
I changed manytomany field to token field with the help of bootstrap tag input javascript plugin. Then I am getting comma (,) separates primary keys as input. After splitting from delimiter comma (,) I got the instance of the exact object. Now how to add those objects to the manytomany field. I tried returning list but it didn't work. Here is my form class class EventRegistrationForm(forms.ModelForm): participants = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'off', 'data-role':'tagsinput'}),required=True) class Meta: model=EventRegistration fields=['event', 'participants', 'teamName', 'feePaid'] def clean_feePaid(self): feepaid=self.cleaned_data.get('feePaid') if not feepaid: raise ValidationError('Please pay the fee First :)') return feepaid def clean_participants(self): participants_data = self.cleaned_data.get('participants') event = self.cleaned_data.get('event') participants =[] for pd in participants_data.split(','): p = Candidate.objects.get(pk=pd) participants.append(p) if not (event.minParticipant <= len(participants) <= event.maxParticipant): raise ValidationError('Number of Participants exceeded :D') return participants def __init__(self, *args, **kwargs): super(EventRegistrationForm, self).__init__(*args, **kwargs) self.fields['event'].empty_label = '' # following line needed to refresh widget copy of choice list self.fields['event'].widget.choices =self.fields['event'].choices -
How can I specify when Sublime Text 3 should use filetype HTML(Django), versus HTML(AngularJS), versus HTML?
I recently installed the Djaneiro package in my installation of Sublime Text 3 to offer me auto completion for Django Templates. It's really helped speed up my django development, however now overrides my basic HTML projects and AngularJS projects to HTML(Django). I'd like Sublime to default HTML format on static HTML projects, HTML Angular on projects that are specifically Angular, and HTML(Django) for other projects. Although not a huge problem, it becomes a nuisance when I'm expecting HTML auto completion and the angular ng tags auto complete, or Django auto complete on standard HTML files. Is there a way to default which HTML File type required for Sublinting I require by project? -
How to update image that is send by Android in base64 image?
I have written an api to post data for Android api. In the request data I am getting images in base64 format. In the modelserializer, I have created image field image_upload = Base64ImageField(required = False) and the image field is read_only and after doing serializer.save(), it converts the image in proper format. Now I want to update the existing image. In the serializer.validated_data I am getting image as None. How to update the existing image that is send in base64 format? Thank you. -
Django migration error, trying to clean up date field with bad default
I have a model: class Season(models.Model): """ Corresponds to your brochure publishing schedule, e.g. Fall/Winter 2012, Sprint 2014, etc. """ name = models.CharField(max_length=45, db_index=True, unique=True) start_date = models.DateField(db_index=True, help_text="The date enrollment can begin this Season.") <snip> The model pre-dates migrations and I didn't use South. The start_date field lived for many years with this definition start_date = models.DateField(db_index=True, default=False, help_text="The date of the first Session of this Season.") I actually went in to edit the help text and noticed the default=False and thought, that doesnt make sense for a date field, it must have been a remnant from when I was dumb. So I took that out. Now my migration: class Migration(migrations.Migration): dependencies = [ ('district', '0012_auto_20160622_1741'), ] operations = [ migrations.AlterField( model_name='season', name='start_date', field=models.DateField(help_text=b'The date enrollment can begin this Season.', db_index=True), ), ] Fails with: Applying district.0013_auto_20170204_1811...Traceback (most recent call last): File "manage.py", line 9, in <module> execute_from_command_line(sys.argv) File "/verylongpathtovenv/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/verylongpathtovenv/lib/python2.7/site-packages/django/core/management/__init__.py", line 346, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/verylongpathtovenv/lib/python2.7/site-packages/django/core/management/base.py", line 394, in run_from_argv self.execute(*args, **cmd_options) File "/verylongpathtovenv/lib/python2.7/site-packages/django/core/management/base.py", line 445, in execute output = self.handle(*args, **options) File "/verylongpathtovenv/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 222, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "/verylongpathtovenv/lib/python2.7/site-packages/django/db/migrations/executor.py", line 110, in migrate self.apply_migration(states[migration], migration, fake=fake, … -
what does members indicate in django rest
when i do a curl curl -H "Authorization: Token <token>" "http://localhost:8000/api/url" I get a response like this {"id":20,"team_name":"something","created_by":"joe","members":[{"member_name":"joe","status":"Self","member_id":1}]}% what does this members array indicate ? Are they foreign key fields of this specific request -
Count # of non-empty fields in Django
I'm trying to make a site where people can create an event, then add pictures (from an outside album, no need to upload), and then I want to pull info about how many pictures are added and display that on a central catalog. For example (excluding some code for brevity's sake): models.py class EventDB(models.Model): picture1 = models.CharField ("picture 1", max_length=255, blank=True) picture2 = models.CharField ("picture 2", max_length=255, blank=True) If someone added an item to EventDB and added 1 picture, I could return the output as 1. If they added 2 pictures, it would return as 2, and so on and so forth. I want to have a central page that lists all the events and has the corresponding number of pictures next to it. For example: Event1 (2) Event2 (1) Event3 (4) where the number in parenthesis is the # of pictures. What would be the best way to do this? I've tried playing around with (picture1__isnull=True).count() but that counts the TOTAL number of items in my DB without a picture1 uploaded. Thanks!! -
Reverse for 'vote' with arguments '(...,)' and keyword arguments '{}' not found.
Intro I am following the Django tutorial and I am not able to make one specific view working. Problem I have defined the detail and vote view. The both view functions in views.py take the same input argument. I will get the "Reverse for 'vote' ... not found" if I in the html template define: {% url 'polls:vote' question.question_id %} Observation If I refer to the detail view: {% url 'polls:detail' question.question_id %} the detail view is shown. Question The detail function takes exactly the same argument as the vote function. Why am I getting the error Reverse for 'vote' not found? What is the difference between these views? Source urls.py: from django.conf.urls import url from . import views app_name= 'polls' urlpatterns = [ url(r'^$',views.index, name='index'), #ex: polls/5/results/ url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'), #ex: /pools/5/volte url(r'^(?P<question_id>(^([a-z|0-9]{8}))(-{1}([a-z|0-9]{4})){3}(-{1}([a-z|0-9]{12})))/vote/$', views.vote, name='vote'), #ex: polls/5/ url(r'^(?P<question_id>[^/]+)/$',views.detail, name='detail'), ] views.py: from django.shortcuts import render # Create your views here. from django.shortcuts import render, get_object_or_404 from .models import Question, Choice def index(request): #latest_question_list = Question.objects.order_by('-pub_date')[5:] latest_question_list = Question.objects() context = { 'latest_question_list': latest_question_list, } return render(request, 'polls/index.html', context) def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question':question}) def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = … -
Setting cookies within Django Middleware
I would like to use Custom Django Middleware (Django 1.9) to check whether or not an anonymous user has accepted a site's terms & conditions - I'll show the user a dialog if they've not yet clicked 'Agree'. I have no need to store this in the database and would prefer to simply use a Cookie. I have the following in settings.py: MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', ... 'myapp.middleware.app_custom_middleware.TermsMiddleware',] SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies' I'm then trying something very rudimentary in TermsMiddleware - here I'm deliberately trying to modify the request and the response just to try to get it to work: class TermsMiddleware(object): def process_request(self, request): request.session.__setitem__('myCookieKey', 'myCookieValue') request.session.save() return def process_response(self, request, response): request.session.__setitem__('myCookieKey', 'myCookieValue') request.session.save() return response If I inspect the response in the browser, I see that myCookieKey isn't being set, so I think I've misunderstood how this should be written. Can I manipulate the session within middleware like this, having it take effect in the cookie sent in the response Django was going to send anyway? The documentation makes it sound like I should be able to: It should return either None or an HttpResponse object. If it returns None, Django will continue processing this request, executing …