Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why the contents of the form changes?
I am tring to create dynamic list to choicesof symbol field. I create that list inside view then put it to form constructor. I want to take all data from Dictionary modal put it inside choices and show in my form but in the same time I dont need to show data which is already exist in Requirement modal. At start it shows form correct: Then when I try to click submit button form changes to this: (Whats wrong happenes?) models.py: class Dictionary(models.Model): symbol = models.CharField(_('Symbol'), max_length=250) name = models.CharField(_('Name'), max_length=250) class Requirement(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) symbol = models.CharField(_('Symbol'), max_length=250) name = models.CharField(_('Name'), max_length=250) forms.py: class RequirementForm(forms.ModelForm): symbol = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple) class Meta: model = Requirement fields = ('symbol',) def __init__(self, final_list, *args, **kwargs): super(RequirementForm, self).__init__(*args, **kwargs) self.fields['symbol'].choices = [(x[0], x[1]) for x in final_list)] views.py: def requirement_add(request, project_code): project = get_object_or_404(Project, pk=project_code) if request.method == 'POST': form = RequirementForm(request.POST) if form.is_valid(): requirement_dict = dict([(x.symbol, x.name) for x in Dictionary.objects.all()]) symbols = form.cleaned_data.get('symbol') requirement = form.save(commit=False) for symbol in symbols: requirement.project = project requirement.symbol = symbol requirement.name = requirement_dict[symbol] requirement.pk = None requirement.save() else: requirements = Requirement.objects.filter(project=project_code) current_list = [] for x in requirements: y = (x.symbol, x.name) current_list .append(y) … -
How to prepopulate test database by necessary data?
I need to do some unit tests in my Django project. The problem is that almost every use case depends on prepopulated database objects. For example, I want to create a product and test, if there were all pre_save signals successful. from django.contrib.auth.models import User from django.test import TestCase from .models import Product class ProductTestCase(TestCase): def setUp(self): self.user = User.objects.create(username='test_user') self.product = Product.objects.create(name='Test product',user=self.user) def test_product_exists(self): self.assertIsNotNone(self.product) def product_is_active_by_default(self): ... I can't do that because product has to have User object related. But I can't create a User object because User has to have related plan object. There are multiple plans in my production database from which one is default but there are no plans inside test database. So to be able to do unit tests I need to prepopulate test database with multiple objects from multiple apps. How can I do that? -
Django - display Json or Httpresponse in template
I have something this in views.py: return JsonResponse({'foo': 'bar'}) How would i display "bar" in the template? Something like: <h1 id="demo"></h1> <script> document.getElementById("demo").innerHTML = ?JsonResponse?; </script> or could it be done with http response? return HttpResponse("Bar") and html: <h1 id="demo"></h1> <script> document.getElementById("demo").innerHTML = ?HttpResponse?; </script> -
django api - Mongo DB vs sqlite
I am working on a program that currently using django framework that is interfacing sqlite db. I am considering moving to Mongo DB but I am finding it diffcult to understand if in addition to all the configuration modifications I will have to change the django api. I trying to minimize the work for this transfer. It is important to say that in the future I might interface with SQL/NOSQL database. is working with Mongo DB still recommended? -
(django) Why do I get an error when adding app to INSTALLED_APPS but not when just importing?
I wrote an app with abstract classes, some utils functions, my common template tags and so on. Somewere I saw it's recommended way to do this stuff to a reusable app. (It's all related to each other.) Why not? It seems to be a good idea. So I made the stuff being part of an app. Since that app has no urls, views and not the normal structur, it's more like a python module. (But it needs django.) When I import this app the normal way (with import myapp on top of the files) it works fine. Looking for bestpractice I saw in the official django tutorial part 8 that's recommended to import apps in INSTALLED_APPS in settings.py. Since I made my utils module being an app I thought I could just add a line to INSTALLED_APPS. Just like this: myapp.apps.MyappConfig. My project structure: project |-... [multiple normal apps] |-myapp [which is my utils app] |-project [the inner folder] |-... [some other stuff] As you can see, myapp, the utils app, is still part of the project (and hasn't been made a reusable app yet.) But when I add that line to INSTALLED_APPS I get the following traceback: Unhandled exception … -
Django passing data from one app to another?
I am using django-allauth for my authentication. I have a dashboard which has many links. example: user.html `{% include 'sidebar.html' %} <h1>Profile View</h1> <p>{{ profile.username }}</p>` change_password.html `{% include 'sidebar.html' %} <h2>Change Password</h2> <p>{{ profile.username }}</p>` sidebar.html `<a href="{% url 'profile_view' slug=profile.username %}">Profile View</a> <a href="{% url 'change_password' %}">Change Password</a>` views.py class ProfileView(DetailView): template_name = "user.html" queryset = User.objects.all() context_object_name = 'profile' slug_field = "username" change password view is from django-allauth. How can i pass the the username from the ProfileView to the change password view so that i can display in the change_password.html page. Main Problem Since i have been including sidebar.html to both the views, it works good in ProfileView but when i navigate to change_password view i get the following error Reverse for 'profile_view' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['(?P[-\w.@+-]+)/$'] the error does not show in ProfileView because the profile.username returns a value, but when i navigate to change_password view i get the above error because the profile context object only passes in that particular view. i want to use that context_object through out the project. Is there a simple way to do it? other than build a JSON API? -
Issue with for cycle in django and javascript
please help, because i failed My problem. I used django, and tried to make replay of comments due their id. Everything is working, but i can get only last item from for cycle via javascript. {% for comment in object_comments %} <li> <article> <div class="comment-avatar"> <img src="images/blog/author.png" class="avatar"> <span class="comment-reply"> <a id='reply' class="comment-reply-link" onClick="a_onClick()">Reply</a> </span> </div> <script> function button_onClick() { $('').click(); } function a_onClick() { window.scrollTo(0,document.body.scrollHeight); document.getElementById('text').value = "{{comment.name}}"; } </script> <div class="comment-body"> <div class="meta-data"> <a href="#" class="comment-author">{{ comment.name }}</a> <span class="comment-date"> {{ comment.pub_date }} </span> </div> <div class="comment-content"> {{ comment.text }} </div> </div> </article> </li> {% endfor %} The getting line is "document.getElementById('text').value = "{{comment.name}}";" I know it's not possible, but maybe u can help to find some workaround. -
Django - post multiple files with ajax
How could I post number between 1-6 and multiple image files with ajax? I would like to do this, because I want to upload files and display errors without refreshing, but I can`t set it up. Is it even possible to upload multiple images without using any external modules, etc, just ajax? Form is in modal. Html: <!-- Modal --> <div class="modal fade" id="myModalHorizontal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <!-- Modal Header --> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"> <span aria-hidden="true">&times;</span> <span class="sr-only">Close</span> </button> <h4 class="modal-title" id="myModalLabel"> Add exam </h4> </div> <!-- Modal Body --> <div class="modal-body"> <form id="form" class="form-horizontal" role="form" method="post" enctype="multipart/form-data" action="{% url 'create_exam' letnik_id=letnik_id classes_id=classes_id subject_id=subject_id %}" id="post-form" onsubmit="myFunction()"> {% csrf_token %} <div class="form-group" csrf="{{ csrf_token }}"> <label class="col-sm-2 control-label" for="inputEmail3">Številka Testa</label> <div class="col-sm-10"> <select class="form-control" id="exam_number" name="exam_number"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> <option>6</option> </select> </div> </div> <div class="form-group"> <label class="col-xs-2 control-label" >Pictures</label><br> <div class="col-sm-10"> <input name="exam_file" type="file" accept="*" multiple required> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> </div> </div> </div> <!-- Modal Footer --> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal"> Close </button> <button class="btn btn-primary" id="form-submit" type="submit"> Add </button> </div> </form> </div> </div> </div> -
How to override SearchForm method in Django Haystack
I aim to have my Django Haystack Whoosh search return all results if no results where found. In Haystack documentation I read that I can override the no_query_found method (see below) in my SearchForm to do this. But I have no idea how. Any ideas? class SearchForm(forms.Form): def no_query_found(self): """ Determines the behavior when no query was found. By default, no results are returned (``EmptySearchQuerySet``). Should you want to show all results, override this method in your own ``SearchForm`` subclass and do ``return self.searchqueryset.all()``. """ return EmptySearchQuerySet() Here's my forms.py: from django import forms from .models import Blog, Category from locations.models import Country, County, Municipality, Village from haystack.forms import SearchForm class DateRangeSearchForm(SearchForm): start_date = forms.DateField(required=False) end_date = forms.DateField(required=False) def search(self): # First, store the SearchQuerySet received from other processing. sqs = super(DateRangeSearchForm, self).search() if not self.is_valid(): return self.no_query_found() # Check to see if a start_date was chosen. if self.cleaned_data['start_date']: sqs = sqs.filter(pub_date__gte=self.cleaned_data['start_date']) # Check to see if an end_date was chosen. if self.cleaned_data['end_date']: sqs = sqs.filter(pub_date__lte=self.cleaned_data['end_date']) return sqs -
Enum type django and rest framework
I have a problem with the rest framework and one enum field. I get this error: File "/usr/local/lib/python2.7/dist-packages/coreapi/codecs/corejson.py", line 48, in decode_schema_from_corejson return schema_cls(title=title, description=description) TypeError: __init__() takes exactly 2 arguments (1 given) when the model has this field: class PuddleAtomStatus(ChoiceEnum): INVALID = "INVALID" OK = "OK" class PuddleAtom(Model): name = models.CharField(max_length=255, primary_key=True) ingestion_flow = models.CharField(max_length=256) status = EnumChoiceField(enm_class=PuddleAtomStaus) but anything is fine when status = models.CharField(max_length=100) I'm using Django 1.11 and python 2.7 Is there a way to fix this and leave the model with the enum field ? -
Error was: cannot import name 'GDALRaster' in windows 8.1
(casino_locater) C:\Users\....\Desktop\Geolocation>python manage.py makemigrations ............. .............. .............. django.core.exceptions.ImproperlyConfigured: 'django.contrib.gis.db.backends.postgis' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' Error was: cannot import name 'GDALRaster' -
Raven - Sentry and Django: AttributeError: 'function' object has no attribute 'send'
I installed raven-python in my django project, the ./manage.py raven test works, but I get a big traceback when I want to load any page of my app (the development server starts correctly): Traceback (most recent call last): File "/home/vince/.virtualenvs/abelujo/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 63, in __call__ return self.application(environ, start_response) File "/home/vince/.virtualenvs/abelujo/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 177, in __call__ signals.request_started.send(sender=self.__class__, environ=environ) File "/home/vince/.virtualenvs/abelujo/lib/python2.7/site-packages/django/dispatch/dispatcher.py", line 201, in send response = receiver(signal=self, sender=sender, **named) File "/home/vince/.virtualenvs/abelujo/lib/python2.7/site-packages/raven/contrib/django/models.py", line 209, in before_request self.client.context.activate() File "/home/vince/.virtualenvs/abelujo/lib/python2.7/site-packages/raven/contrib/django/models.py", line 55, in <lambda> __getattr__ = lambda x, o: getattr(get_client(), o) File "/home/vince/.virtualenvs/abelujo/lib/python2.7/site-packages/raven/contrib/django/models.py", line 135, in get_client instance = Client(**options) File "/home/vince/.virtualenvs/abelujo/lib/python2.7/site-packages/raven/contrib/django/client.py", line 138, in __init__ Client.__init__(self, *args, **kwargs) File "/home/vince/.virtualenvs/abelujo/lib/python2.7/site-packages/raven/base.py", line 222, in __init__ self.hook_libraries(hook_libraries) File "/home/vince/.virtualenvs/abelujo/lib/python2.7/site-packages/raven/base.py", line 275, in hook_libraries hook_libraries(libraries) File "/home/vince/.virtualenvs/abelujo/lib/python2.7/site-packages/raven/breadcrumbs.py", line 364, in hook_libraries func() File "/home/vince/.virtualenvs/abelujo/lib/python2.7/site-packages/raven/utils/__init__.py", line 185, in new_func rv = func(*args, **kwargs) File "/home/vince/.virtualenvs/abelujo/lib/python2.7/site-packages/raven/breadcrumbs.py", line 286, in _hook_requests real_send = Session.send AttributeError: 'function' object has no attribute 'send' I don't know where to investigate. Any idea what's going on ? Thanks. raven/django documentation (I don't use the client defined at the end of the setup). I use django-whitenoise to serve static files, setted on wsgi.py but it does not appear to have any influence (I disabled it). … -
Setting intial values in Django Form
I have a Django form: class PlayerForm(forms.Form): OPTIONS = MyUser.objects.all() players = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=OPTIONS) I want the initial values of the players to be checked if MyUser.player = True. How do I set these initial values? -
(django) get query of child class
I have a super class like this: class Superclass(models.Model): number = models.PositiveIntegerField() class Meta: abstract = True def get_next(self): return Superclass.objects.get(number=self.number+1) Now, I have a child class that inherits from the superclass. What's the problem? I can't do this: Superclass.objects because the superclass doesn't refer to any database table. I don't want to query all Superclass childs, only the one of the current child class, like this: When I do instance_of_child1.get_next I don't want to get an instance of Child2. How to solve this? My first idea was to add a static constant to any child class that contains the class (So I could do self.myclass.objects) But this seems to be not a good way. Make the method get_next being part of the child class. Problem: there will be duplicates. -
Why css for admin url in python-django project could not loading?
I am new to python & django. I have learnt basic of both and made a simple project called PythonDjangoDemo. I have visited admin urls during development. But I am unable to load css for admin url in python-django project. At first lets look at project structure. I have - PythonDjangoDemo |--- PythonDjangoDemo | |--- __init__.py | |--- settings.py | |--- urls.py | |--- wggi.py |--- static_cdn | |--- admin | | |--- css | | | |---base.css | | | |---login.css | | |--- fonts | | |--- img | | |--- js |--- media_cdn |--- templates |--- manage.py |--- db.sqlite3 Let's have a look at settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ... ... ... STATIC_URL = '/static/' MEDIA_URL = "/media/" STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn") MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media_cdn") I have putted all my css for admin urls at "static_cdn/admin/css". While I am trying to access "127.0.0.1:800/admin" then I do not get any error(s). Here is the console output - [30/Apr/2017 16:04:58] "GET /admin/ HTTP/1.1" 302 0 [30/Apr/2017 16:04:59] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 1650 [30/Apr/2017 16:04:59] "GET /static/admin/css/base.css HTTP/1.1" 200 16066 [30/Apr/2017 16:04:59] "GET /static/admin/css/login.css HTTP/1.1" 200 1203 Not Found: /favicon.ico [30/Apr/2017 16:04:59] "GET … -
Django autocomplete-light v3 from db
I've already make it directly in HTML page with Jquery but I think isn't a good solution due to the big item list. I think it's better have a huge list stored in the db and than autocompile the field in my case. I want autocompile (with airport name) two field (departure and destination). So in models.py I make two class: class Aero(models.Model): departure = models.CharField(max_length=20) destination = models.CharField(max_length=20) class AirportName(models.Model): air_name= models.CharField(max_length=70) I populate the db with 3000 airport (I use AirportName class to do that). Now I would like that when a user start to digit in departure or destination field (in a form), it will appear the possibile match airport list. I read the documentation but I don't understand how do that, maybe I mistake everything. url.py: url( r'^fly-autocomplete/$', Fly.as_view(), name='fly-autocomplete', ), views.py: class Fly(autocomplete.Select2QuerySetView): def get_queryset(self): form = AeroForm() qs = AirportName.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs forms.py: class AeroForm(forms.ModelForm): class Meta: model = Aero fields = ('__all__') widgets = { 'departure': autocomplete.ModelSelect2(url='fly-autocomplete'), 'destination': autocomplete.ModelSelect2(url='fly-autocomplete'), } -
Django: 'ManyToManyDescriptor' object has no attribute 'create'
I have two classes in models.py class Account(models.Model): ... class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) accounts = models.ManyToManyField(Account, blank=True) Now in my views.py I have: def create_account(request): account = Account(symbol=request.POST['symbol']) account.save() However, when the form that calls the create_function is successfully submitted, my Django debug mode throws the error: 'ManyToManyDescriptor' object has no attribute 'create', and SELECT * FROM the relevant table in my database confirms that no row has been added. After searching this error online, I can confirm that this probably has to do with the fact that the Profile class is many-to-many associated with the Account class and that I should be creating Account objects differently, however I am not sure how to do it correctly. -
Django MEDIA not serving despite configuration
I know this is a prevalent topic, but I still have yet to find a recent answer that helps. I have setup my dev environment to serve MEDIA in what I believe is the correct way, but images are still not resolving. Paths being return propery in template, but I believe the issue is with URLS.PY? This is my settings.py: if DEBUG: #For local STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') if DEV: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' ADMIN_MEDIA_PREFIX = 'http:/127.0.0.1:8000/admin-media/' This is the template itself (attached image is the rendered template itself, which seems correct): <div><img src="{{MEDIA_URL}}products/{{product.filename}}"></div> This is my primary URLS.py (top level, not application specific, but I've added this line in the app specific one as well): urlpatterns = [ url(r'^', include('drivel.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^tinymce/', include('tinymce.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) What am I missing? I am down to the wire and can't seem to get this going. I also am open to recos for the production site as I'm new to Django and best practices in production. Environment is Py 2.7, Django 1.8. enter image description here -
Django - display Json response in template
In views.py i have: return JsonResponse({'foo': 'bar') How can i "capture" that Json response in template and display it inside <h1> </h1>? -
Django admin static files
I want to deploy a server using nginx, django & gunicorn. I created a django project in /home/myproj/ with STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static'), did all the migrations, and then python3 manage.py collectstatic then I changed the nginx configuration: server { listen 80; server_name www.myserver.com; access_log /home/nginx.log; location /static/ { alias /home/myproj/static/; autoindex on; expires 30d; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } when I start the server gunicorn myproj.wsgi:application the start page is displayed correctly, but the admin panel does not load the css styles. What am I doing wrong? I've also noticed that if in settings.py -> debug = False, I get a 404 error P.S. I'm still not good in linux, so please write the full commands. -
Not getting the nav parent-page active when I'm in child-page
Parent page is good like so: When I click on the child page it does not behave like parent does: Although I have the base.html in child page it wont show as wished. I have tried several solutions with no luck so hopefully you can guide me in the right way. Still a newbie and appreciate all your help, folks! base.html <script> $(document).ready(function() { $('li.active').removeClass('active'); $('a[href="' + location.pathname + '"]').closest('li').addClass('active'); }); </script> ... <ul class="nav navbar-nav"> <li class="active"><a href="{% url 'member_overview' %}"> {% trans 'Members' %}</a></li> ... </ul> member_overview.html {% extends 'base.html' %} ... <div class="row"> <a class="btn btn-primary btn-lg" href="{% url 'member_signup' %}"> <span class="glyphicon glyphicon-plus" aria-hidden="true"></span> {% trans 'New Member' %} </a> </div> ... member/urls.py (if it helps) urlpatterns = [ url(r'^member_overview/$', views.member_overview.as_view(), name='member_overview'), url(r'^member_signup/$', views.member_signup, name='member_signup'), ... ] -
Django not response to Ajax call while doing a computing intensive task
I am recently using Django to program my web interface for my "scientific computing engine". I wrap the "computing engine" as a python module and call it inside the Django Framework. The compute() function of the "engine" takes several minutes to run (I use ajax to trigger it) , at the same time, I let the front-end make extra ajax call every 0.5 second to update the CPU and Memory status to the front-end. But I find the server is not respond to the extra ajax call until the compute() finishes. After search around, I think I might use the idea of asynchronous or multithreading so I make the function in views.py like below. def submit(request): #some prepare ........ # call the engine t = Thread(target = compute) t.start() return HttpResponse("started") But the system still not response to my extra ajax call until the compute() finish (The "engine" only use around 20% of the CPU, so there is plenty of computing power left). I am a newbie in back-end programming, I am not sure about how Django or backend server handle request internally. Thank you so much if anyone can give me some hint about how to handle this situation. -
OperationaLError MySQL Failed to Connect With Localhost
I'm having a very hard time in making MySQL work again. I installed MySQL server and was able to get it to work at first. When navigating through my site, I got the below error. OperationalError at / (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)") I changed the bind-address to localhost, yet it failed to pick up. read through different answers online, yet none worked for me. I'm still finding hard to figure out why it stopped working all of a sudden. When I run this command sudo service MySQL restart, I will get the below error, Job for mysql.service failed because the control process exited with error code. See "systemctl status mysql.service" and "journalctl -xe" for details. When I run the systemctl status mysql.service, I get the below error details, mysql.service - MySQL Community Server Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset: en Active: activating (start-post) (Result: exit-code) since Sun 2017-04-30 11:4 Process: 12946 ExecStart=/usr/sbin/mysqld (code=exited, status=1/FAILURE) Process: 12937 ExecStartPre=/usr/share/mysql/mysql-systemd-start pre (code=exi Main PID: 12946 (code=exited, status=1/FAILURE); : 12947 (mysql-systemd Tasks: 2 Memory: 328.0K CPU: 406ms CGroup: /system.slice/mysql.service └─control ├─12947 /bin/bash /usr/share/mysql/mysql-systemd-start post └─13009 sleep 1 See my config [mysqld_safe] socket = /var/run/mysqld/mysqld.sock nice = … -
How do I upload files of arbitrary size to mezzanine.core.fields.FileField
The featured image on the mezzanine.blog.models.BlogPost content type is of type mezzanine.core.fields.FileField. When I try to upload a featured image there is a 2.5MB limit on the size of the file. Where is this value defined? I want to increase or remove this restriction. -
Disable or hide an entry from model temporarily in Django
How can it be possible to disable or hide an entry from model temporarily when certain conditions are satisfied in the view function like if statement.