Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Context processor not being run on login page?
I have created a context processor which aims to pass a certain variable to any template that gets loaded. This is how I have defined my context processor: from django.conf import settings def theme(request): return {'custom_theme': getattr(settings, "CUSTOM_THEME", "default")} This is how I have included my context processor in the settings file: TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'DIRS': [ normpath(join(PROJECT_PATH, 'templates')), ], 'OPTIONS': { 'context_processors': { 'django.template.context_processors.request', 'django.template.context_processors.media', 'django.contrib.auth.context_processors.auth', 'myapp.context_processor.theme', }, 'debug': False, } }] However, for some reason, it is not always being executed, mainly in the login page. This is the view that handles the login URL and return a 'TemplateResponse`: @never_cache @sensitive_post_parameters('password') @csrf_protect def custom_login(request): redirect_field_name = 'next' redirect_to = request.POST.get(redirect_field_name, request.GET.get(redirect_field_name, '')) if request.method == "POST": form = AuthenticationForm(request, data=request.POST) if form.is_valid(): # Ensure the user-originating redirection url is safe. if not is_safe_url(url=redirect_to, host=request.get_host()): redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL) # Okay, security check complete. Log the user in. auth_login(request, form.get_user()) if getattr(settings, 'CHECK_PERMISSIONS_ON_CMDB', False): logger.info('Checking permissions on CMDB.') auth_cmdb_user_realms(form.get_user()) return HttpResponseRedirect(redirect_to) else: form = AuthenticationForm(request) context = { 'form': form, 'version': get_project_version(), redirect_field_name: redirect_to, } if hasattr(settings, "CUSTOM_THEME"): login_template = 'custom_auth/themes/{}/login.html'.\ format(settings.CUSTOM_THEME) else: login_template = 'custom_auth/themes/default/login.html' return TemplateResponse(request, login_template, context) Since the context processor is not … -
How can I link an edit page to my detail profile page in django?
So I am trying to link the template where I can edit a user_profile like this: Edit But is giving me this error: NoReverseMatch at /user_profile/9/ Reverse for 'user_profile_update' with arguments '()' and keyword arguments '{u'id': ''}' not found. 1 pattern(s) tried: [u'user_profile/(?P\d+)/edit/$'] But I can get access to the template like this without an error: /user_profile/(id)/edit This is my view: def user_profile_update(request, id=None): instance = get_object_or_404(user_profile, id=id) form = user_profileForm(request.POST or None, request.FILES or None, instance=instance) if form.is_valid(): instance = form.save(commit=False) instance.save() return HttpResponseRedirect(instance.get_absolute_url()) context = { "first_name": instance.first_name, "instance": instance, "form":form, } return render(request, "user_profile/user_profile_form.html", context) This is my url: url(r'^(?P\d+)/edit/$',user_profile_update, name='edit'), And this is my model: class user_profile(models.Model): first_name = models.CharField(null=True,max_length=100) last_name = models.CharField(null=True,max_length=100) address_1 = models.CharField(_("Address"), max_length=128) address_2 = models.CharField(_("Address 1"), max_length=128, blank=True) city = models.CharField(_("City"), max_length=64, default="pune") country_name = models.CharField(max_length=60) pin_code = models.CharField(_("pin_code"), max_length=6, default="411028") updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) def __unicode__(self): return self.first_name def __str__(self): return self.first_name def get_absolute_url(self): return reverse("user_profile:detail", kwargs={"id": self.id}) class Meta: ordering = ["-timestamp", "-updated"] I would be really glad if someone could help me! -
Django migration error match = date_re.match(value) TypeError: expected string or buffer
Here is my model class Bob(models.Model): STATUS = ( ('0', 'Locked'), ('1', 'Ongoing'), ('2', 'Completed'), ) user = models.ForeignKey(User, related_name='completed_tasks') hunt = models.ForeignKey(ScavengerHunt, on_delete=models.CASCADE) task = models.ForeignKey(Tasks, related_name='completed_scavenger_tasks') start_date_time = models.DateField(auto_now_add=True) completed_date_time = models.DateField(null=True, blank=True) status = models.CharField(max_length=10, choices=STATUS, default='start') image = models.ImageField(upload_to='api/scavenger/tasks/', null=True, blank=True) i am getting when i try to migrate this error: match = date_re.match(value) TypeError: expected string or buffer I have searched and it occurs when if i add invalid parameters to datefield but mine has only blank,null and verbose..what seems to be the problem? The schemamigration is def forwards(self, orm): # Deleting field 'TrackCompletedScavangerTasks.completed_date_time' db.delete_column(u'api_trackcompletedscavangertasks', 'completed_date_time') # Adding field 'TrackCompletedScavangerTasks.hunt' db.add_column(u'api_trackcompletedscavangertasks', 'hunt', self.gf('django.db.models.fields.related.ForeignKey')(default=1, to=orm['api.ScavengerHunt']), keep_default=False) # Adding field 'TrackCompletedScavangerTasks.completed_date' db.add_column(u'api_trackcompletedscavangertasks', 'completed_date', self.gf('django.db.models.fields.DateField')(null=True, blank=True), keep_default=False) # Deleting field 'ScavengerHunt.end_date_time' db.delete_column(u'api_scavengerhunt', 'end_date_time') # Deleting field 'ScavengerHunt.start_date_time' db.delete_column(u'api_scavengerhunt', 'start_date_time') # Adding field 'ScavengerHunt.start_date' db.add_column(u'api_scavengerhunt', 'start_date', self.gf('django.db.models.fields.DateField')(default=1), keep_default=False) # Adding field 'ScavengerHunt.end_date' db.add_column(u'api_scavengerhunt', 'end_date', self.gf('django.db.models.fields.DateField')(default=1), keep_default=False) def backwards(self, orm): # Adding field 'TrackCompletedScavangerTasks.completed_date_time' db.add_column(u'api_trackcompletedscavangertasks', 'completed_date_time', self.gf('django.db.models.fields.DateField')(null=True, blank=True), keep_default=False) # Deleting field 'TrackCompletedScavangerTasks.hunt' db.delete_column(u'api_trackcompletedscavangertasks', 'hunt_id') # Deleting field 'TrackCompletedScavangerTasks.completed_date' db.delete_column(u'api_trackcompletedscavangertasks', 'completed_date') # Adding field 'ScavengerHunt.end_date_time' db.add_column(u'api_scavengerhunt', 'end_date_time', self.gf('django.db.models.fields.DateField')(default=1), keep_default=False) # Adding field 'ScavengerHunt.start_date_time' db.add_column(u'api_scavengerhunt', 'start_date_time', self.gf('django.db.models.fields.DateField')(default=1), keep_default=False) # Deleting field 'ScavengerHunt.start_date' db.delete_column(u'api_scavengerhunt', 'start_date') # Deleting field 'ScavengerHunt.end_date' db.delete_column(u'api_scavengerhunt', 'end_date') -
Proper way to retrieve middleware values
I'm trying to retrieve some loading times per view and displaying it in the page. To do so I'm using a middleware and a context_processor setup but I can't find the way to retrieve this values to the context of the view. Here is the example: I've added the middleware and context_processor to the settings. middlewares.py (from this answer): from __future__ import unicode_literals, absolute_import from django.db import connection from time import time from operator import add import re from functools import reduce class StatsMiddleware(object): def process_view(self, request, view_func, view_args, view_kwargs): # get number of db queries before we do anything n = len(connection.queries) # time the view start = time() response = view_func(request, *view_args, **view_kwargs) total_time = time() - start # compute the db time for the queries just run db_queries = len(connection.queries) - n if db_queries: db_time = reduce(add, [float(q['time']) for q in connection.queries[n:]]) else: db_time = 0.0 # and backout python time python_time = total_time - db_time stats = { 'total_time': total_time, 'python_time': python_time, 'db_time': db_time, 'db_queries': db_queries, } # this works fine print(stats) # replace the comment if found if response: try: # detects TemplateResponse which are not yet rendered if response.is_rendered: rendered_content = response.content else: rendered_content … -
How to allow DELETE request in the list-view of Django REST framework ? Is it possible?
Is it possible to delete List of objects from Django rest framework list-view ? I am passing list of ids of objects [1,2] in delete request and its showing {u'detail': u'Method "DELETE" not allowed.'}. Allowed methods at List-view are :GET, POST, HEAD, OPTIONS I want to add DELETE to this allowed reuqest. -
In Djnago , is it preferrable to have multiple apps with single model.py, if data model follows EAV-CR pattern? If not, what is the other way?
I am buidling a Django project. The metadata gets stored in Django models.py. I have different apps in the single project. Each app handles it's own set of responsibilities. The data model that has been followed here is EAV-CR. I read that we can have both approaches as many apps single model and many apps many models. But my question is , in my siuation what is the preferable way to do it? I am bit confused since the data model is EAV. (There only 4-5 tables in models.py). This may be a simple or stupid question, but I am really not sure how to tackle it, since it's my first time to deal with many apps in single project. Furthurmore, if we prefer single model with many apps, how the communication between many apps will be done? Is there any best practice to do so? Your kind help will be really appriciated. If I am not asking question in proper way, kindly let me know I will edit it. Thanks a lot. -
Jquery download file and additional callback
I have form which i submit to django server by calling. $("#my_form").submit(); It server returns xml file by executing this code: content = some_data_retrieved_from_database_as_xml() response = HttpResponse(content, content_type='text/xml') response['Content-Disposition'] = 'attachment; ' response['Content-Disposition'] += 'filename=my_file.xml' response['Content-Encoding'] = 'UTF-8' return response Google Chrome only downloads this file, but i want register additional callback function, called myFunction(data). Chrome should download this file and next call myFunction(this xml file). I tried this code, but it doesn't work: $("#my_form").bind('ajax:complete', myFunction); I also tried to use $.post, but after that only callback function is called and unfortunatelly my file is NOT downloaded. -
How to use django trans on {% include with %} for different templates
I have this index.html as {% load i18n %} <h1>{% trans 'Hello' %}</h1> <p>{% trans 'Welcome to my site.' %}</p> <p>{% trans title %}</p> <p>{% trans 'hola amigo' %}</p> {% blocktrans %} {% include 'languages/popup.html' with popup_test="Hai i am gonna be tested on trans" %} {% endblocktrans %} my popup.html has <p>{{ popup_test }}</p> I have many templates which include my popup.html, but with different popup_test values. I am translating the pages to german. I could not generate msgid on my django.po file for the blocktrans popup. How could I implement blocktrans on this type of scenario ? I could not generate msgid on my django.po file for the blocktrans popup. -
django rest swagger 2.0.7, I can't use the Post method
the display for Swagger UI: enter image description here enter image description here and the parameters about settings.py for SWAGGER_SETTINGS: SWAGGER_SETTINGS = { 'SECURITY_DEFINITIONS':{ 'basic':{ 'type':'basic' } }, 'APIS_SORTER': 'alpha', 'DOC_EXPANSION': None, 'JSON_EDITOR':'True', 'OPERATIONS_SORTER':'alpha', 'SHOW_REQUEST_HEADERS':False, 'SUPPORTED_SUBMIT_METHODS':['get','post','put','delete','patch'], 'VALIDATOR_URL':'0.0.0.0:8080', } Have someone help me solve this problem? -
How to get lastest result for each of distinct list?
I have a PostgreSQL table. I can get distinct products and brands: SELECT DISTINCT product, brand FROM list And after it in Django I get the latest price: for x in query: SELECT price FROM list WHERE product = x.product AND brand = x.brand ORDER BY ... LIMIT 1 How can I get all of it by one query? -
Django bulk_create of large datasets with foreign keys
I have a problem of creating a big amount of data with foreign keys in Django ORM on MySql. Let's say I have 2 models: class Student(models.Model): school = models.ForeignKey(School, related_name="students") name = models.CharField(max_length=200, blank=True, default="") class School(models.Model): name = models.CharField(max_length=200, blank=True, default="") Now I want to create a lot of schools that have a lot of students, and lets assume I already have a Data structure that have all the needed info for the creation of it. The only way I found out so far is to create all the schools (in order to get the PK) and on the go to create a list of all the students(in all of the schools) and use bulk_create to create the students. It seems that there should be a better way to do this. Because if for example we have 10K schools and 200 students in school the lowest I managed to do is ~10K inserts and that is to much. Thank you in advance. -
Angular Gulp with Nginx on AWS on Ubuntu
I have been developing a website that has a structure as follows - Django rest app for backend that serves json to the front-end according to what has been requested. AngularJS app for the frontend which requests those apis. Now both backend and frontend are not coupled in any way and locally I used to manage.py runserver the backend and gulp serve the frontend. I am moving to development now and I have set up nginx with aws to run django and cater to api requests, which is working fine. But for the frontend, I am confused as- What gulp serve does is, it injects all the scss and dependencies and starts up the app. How would I start the app using nginx(basically gulp serve)? How would I get django and angular runnung on nginx on the same instance? It would be nice if someone post some examples too. -
Dynamically builing reverse URL with parameters in template
I am using JSGrid in multiple sites in my app. The different JSGrid implementations are very similar, except that the fields to display the webservice to call the url for the onClick action change. Therefore I implemented a JavaScript function in my layout.html that looks as following: layout.html <script type="text/javascript"> function loadJSGrid (_api, _fields, _detailItemReverseUrl) { api = _api || ""; fields = _fields || ""; detailItemReverseUrl = _detailItemReverseUrl || ""; $("#jsGrid").jsGrid({ ... rowDoubleClick: function (item) { window.location.href = detailItemReverseUrl; }, controller: { loadData: function(filter) { var d = $.Deferred(); $.ajax({ type: "GET", url: _api, data: filter }).done(function(result) { d.resolve($.map(result, function(item) { return $.extend(item.fields, { id: item.pk }); })); }); return d.promise(); }, }, fields: _fields, }); } </script> {% block scripts %}{% endblock %} in site.html I am calling this function the following way: {% block scripts %} <script> $(function() { fields = [ { name: "name", type: "text", title:"Namee", width: 150 }, ]; {% with name='loboqms:organization'} {% url {{name}} as the_url %} loadJSGrid ("/loboqms/api", fields, {{the_url}}); }); </script> {% endblock %} The problem now is: I don't know the full reverse link at the time of calling. I know the link (e.g. polls:detailPoll) but I don't know the … -
Multiple User type with Django
We have a very hard time to figure out how we can implement multiple usertypes in Django. We have two types of Users (Teachers and Students) with common fields and uncommon fields In our wizard we first POST the common fields to /users with an extra type_field Every operation after this should be able to figure out which model (Teacher or Student) it needs to use. We are thinking of making two models ( Teacher and Student ) with an one-to-one field. But how do we hookup the type_field to the right Model on every operation? -
utf-8' codec can't decode byte 0xff in position 0
When l use pip install Pillow,it showed me UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc1 in position",and the same problem when i pip other modules,so how can i solve it? -
How to wrap functions in try/except and require a parameter
I want to wrap a bunch of functions in a try/except and have them email me a traceback when they fail. I'm using Django's ExceptionReporter, so I need the request object to send the traceback email. Some of the functions I want to wrap have the request object as a parameter already, but not all of them. I was thinking about using a decorator for the try/except, but then it isn't clear that the request object is a required parameter for all the functions it decorates. Is there a better way to do this? -
django admin required decorator why is it so difficult
I have some questions: Who pass the argument fun in? And what is it? admin_required function returns auth -
Where should i put django application folder
I have followed several django tutorials on the web. There is 2 folders: One for django project and another for application. We can have multiple applications for the same project but i my case, i have just one. Sometimes, the application folder is located at the same level than project folder and sometimes, the application folder is located inside project folder. I do not know what is the best solution... It works in both case. It is just a state of the art question Thanks -
Django, mod_wsgi, apache2 and Ubuntu 12.04
I know there are lot Of questions in SO on this issue. But none of them really helped me to solve this issue. I want to use Apache server with django in ubuntu 12.04. But I could not get it working: sample is the project name sample.wsgi: path: /var/www/sample/sample.wsgi import os import sys path = '/var/www' if path not in sys.path: sys.path.insert(0, '/var/www') os.environ['DJANGO_SETTINGS_MODULE'] = 'sample.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() sample.com file in /etc/apache2/sites-available/sample.com <VirtualHost *:80> ServerName sample.com ServerAlias www.sample.com DocumentRoot /var/www/sample <Directory /var/www/sample> Order allow,deny Allow from all </Directory> WSGIProcessGroup sample.com WSGIScriptAlias / /var/www/sample/sample.wsgi I can run django server but it is not working with apache2 server. -
MPLD3/Django - Why is the graph not showing up?
I converted my MPLD3 into a JSON Dict and inputed the dict into my template to graph it using the function draw_figure. However, the actual JSON dict (a block of text) is displayed in the webpage instead. Why is it doing this? Here is my view.py: js_data = json.dumps(mpld3.fig_to_dict(fig)) return render(request, 'layout.html', {"Graph": js_data}) Here is my template: {% load render_table from django_tables2 %} <!doctype html> <html> <div> graph = {{ Graph|safe }}; mpld3.draw_figure("Figure", graph); </div> </html> -
Django href template joining the complete domain with the MAGNET link whereas only the magnet link should be opened
On clicking the above link while running server, the django domain attaches to it , like http://127.0.0.1:8000/torrent/11372750/Hooked__How_to_Build_Habit-Forming_Products/magnet?xt=urnbtih370d7414aa821678124317d34128617dce7cc6ad&dn=Hooked%3A+How+to+Build+Habit-Forming+Products&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Fzer0day.ch%3A1337&tr=udp%3A%2F%2Fopen.demonii.com%3A1337&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Fexodus.desync.com%3A6969 whereas I just want it to start from the magnet part and also I'm not able to redirect it to that particular part. -
Django Rest Setup for Foreign key values
I have an alert system for the users. users can subscribe to the categories and based on that i will generate alert. I have defined the Models for alert like this. class City(models.Model): name = models.CharField(max_length=25) def __unicode__(self): return self.name class Area(models.Model): name = models.CharField(max_length=25) city = models.ForeignKey(City) def __unicode__(self): return self.name class Category(models.Model): name = models.CharField(max_length=25) def __unicode__(self): return self.name class SubscribeAlert(models.Model): category = models.ForeignKey(Category) user = models.ForeignKey(settings.AUTH_USER_MODEL) status = models.BooleanField(default=False) attributes = JSONField('Subscriptions', null=True, blank=True) class SubscribeLocation(models.Model): subscribe = models.ForeignKey(SubscribeAlert) area = models.ForeignKey(Area) Users can choose the category and select multiple area for the notification. Is this my model structure is ok for this scenario ? And How can I define rest ModelSerializer insert SubscribeAlert and many SubscribeLocation at the same time.? class NotifyCreateSerializer(ModelSerializer): class Meta: model = SubscribeAlert How can I extend this to create the subscription ? Thanks in advance. -
Django : Why does uploading too slow?
I have a Django App running in Compute Engine(GCE) and my problem is that everytime I upload a not so large file like 1MB, the upload time is more than a minute and there are time that it would take almost 2minutes. Is this normal? or I have mis-configuration somewhere in my code like maybe in Nginx. Django : 1.8 Python : 2.7 Compute Engine instance : n1-standard-2 (2 vCPUs, 7.5 GB memory) NginX with uwsgi P.S. My internet connection works fine. Thanks! -
How to annotate field by filer from manytomanyfield
my models class Project(models.Model): name = models.CharField(max_length=255, unique=True) info = models.CharField(max_length=255, unique=True) m2mStatus = models.ManyToManyField("ProjectStatus") class ProjectStatus(models.Model): status = models.BooleanField(default=False) startTime = models.DateTimeField(auto_now=True) description = models.CharField(max_length=255) I want to annotate like this: pj = Project.objects.filter(name="abc") ps = pj.m2mStatus.last() Project.objects.filter(name="abc").annotate(status=ps.status) any help ? -
python - Django AttributeError when try to migrate
When I try to run python manage.py makemigrations, python manage.py migrate or even python manage.py createsuperuse i caught a error AttributeError: '_io.BufferedWriter' object has no attribute 'encoding'. I think this is a problem with manage.py script because i was try migrate with different db and every time i was have a same problem. Traceback: Traceback (most recent call last): File "webapp\manage.py", line 10, in <modu execute_from_command_line(sys.argv) File "\AppData\Local\Programs\Python\Python35\lib\site-packages utility.execute() File "\AppData\Local\Programs\Python\Python35\lib\site-packages self.fetch_command(subcommand).run_from_argv(self.argv) File "\AppData\Local\Programs\Python\Python35\lib\site-packages self.execute(*args, **cmd_options) File "\AppData\Local\Programs\Python\Python35\lib\site-packages return super(Command, self).execute(*args, **options) File "\AppData\Local\Programs\Python\Python35\lib\site-packages output = self.handle(*args, **options) File "\AppData\Local\Programs\Python\Python35\lib\site-packages username = self.get_input_data(self.username_field, input_msg, default_usern File "\AppData\Local\Programs\Python\Python35\lib\site-packages raw_value = input(message) File "\AppData\Local\Programs\Python\Python35\lib\codecs.py", l return getattr(self.stream, name) AttributeError: '_io.BufferedWriter' object has no attribute 'encoding'