Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding custom parameter to django modelform
I'm having troubles adding a custom parameter to a modelform (in this case, the currrent user from request.user) I used to do this on previous projects, and I can't manage to make it work on a new project on Django 1.10.4. I got this error : TypeError at /realestateprogram/edition_appartement/19/ __init__() got an unexpected keyword argument 'user' This is my view : apartment = get_object_or_404(Apartment, pk=apartment_id) if request.method == 'POST': form = ApartmentForm(request.POST, request.FILES, instance=apartment, user=request.user) if form.is_valid(): form.save() return redirect('list_realestateprogram_apartment', realestateprogram_id=apartment.realestateprogram.id) else: print form.errors else: form = ApartmentForm(instance=apartment, user=request.user) and this is my form : class ApartmentForm(forms.ModelForm): class Meta: model = Apartment exclude = ('realestateprogram',) def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(ApartmentForm, self).__init__(*args, **kwargs) Thanks in advance if you can help me -
Nginx and Django Rest Framework - Malformed Json
I'm using nginx + uwsgi to support a Django Rest Framework application. Since I applied nginx server to my project I started to receive malformed Jsons. I bumped into this conclusion when I tested the native Django server and everything worked fine, but when I turn nginx's server on I receive malformed Jsons. application_nginx.conf upstream django { server unix:///home/ubuntu/projetoFidelidade/tottem/encantt.sock; } server{ listen 80; server_name 52.67.199.228; charset utf-8; #max upload size client_max_body_size 75M; # Django Midia location /media{ alias /home/ubuntu/projetoFidelidade/tottem/static/media; } #css, creio que nao sera necessario, mas num futuro pode se expandir a um site location /css{ alias /home/ubuntu/projetoFidelidade/tottem/static/css } #static locationi /static{ alias /home/ubuntu/projetoFidelidade/tottem/static; } #todos requests que nao sejam de midia location /{ uwsgi_pass django; include /home/ubuntu/projetoFidelidade/tottem/uwsgi_params; } } mime.types types { text/html html htm shtml; text/css css; text/xml xml; image/gif gif; image/jpeg jpeg jpg; application/javascript js; application/atom+xml atom; application/rss+xml rss; text/mathml mml; text/plain txt; text/vnd.sun.j2me.app-descriptor jad; text/vnd.wap.wml wml; text/x-component htc; image/png png; image/tiff tif tiff; image/vnd.wap.wbmp wbmp; image/x-icon ico; image/x-jng jng; image/x-ms-bmp bmp; image/svg+xml svg svgz; image/webp webp; application/font-woff woff; application/java-archive jar war ear; application/json json; application/mac-binhex40 hqx; application/msword doc; application/pdf pdf; application/postscript ps eps ai; application/rtf rtf; application/vnd.apple.mpegurl m3u8; application/vnd.ms-excel xls; application/vnd.ms-fontobject eot; application/vnd.ms-powerpoint ppt; application/vnd.wap.wmlc … -
Error in deploying python-django app with Apache and mod_wsgi in RHEL
I am unable to deploy Django-Python application with Apache and mod_wsgi in RHEL. Below is my configuration: Alias /static /home/appuser/xxxweb/yyydep/app/static <Directory /home/appuser/xxxweb/yyydep/app> Require all granted </Directory> <Directory /home/appuser/xxxweb/yyydep/app/management> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess management python-path=/home/appuser/xxxweb/yyydep python-home=/home/appuser/xxxweb/yyydep/disneyenv WSGIProcessGroup management WSGIScriptAlias / /home/appuser/xxxweb/yyydep/app/management/wsgi.py After restarting the apache server below is the error which has been logged. Security update check failed: Couldn't connect to server for https://securitycheck.phusionpassenger.com:443/v1/check.json (if this error persists check your connection security or try upgrading Passenger) (next check in 24 hours) ImportError: No module named site Can any of them help me to resolve this? Thanks -
Django - get data from foreign key
I'm working on a Django project and attempting to create some linked models for my data which In think is working, but I cannot seem to work out how to access the linked data. class One(models.Model) name = models.CharField(max_length=50) list = models.ArrayField(models.CharField(max_length=50), blank=True) def __str__(self): return self.name class Many(models.Model) name = models.CharField(max_length=50) related = models.ForeignKey(One, null=True, blank=True) def __str__(self): return self.name This is the general relationship I have set up. What I am trying to do is, in a template have access to a list of 'Ones', and via each of those, can access each Many and it's related attributes. I can see how to access the attributes for a single 'One', but not how to pass all of them and their related 'Many' models and the related attributes for each. Essentially the output I'd like would have a drop down list with the One's, and when this is submitted some Javascript will use the list in the 'Many' model to do some stuff. Any advice would be much appreciated. -
Celery beat not discovering tasks
I have tasks that I run with celery in my application. I set it up without stress in my dev environment and it was It was working perfectly with redis as a broker. yesterday I transferred the code to my server and setup redis but celery cannot discover the tasks. The code is just the same. My celery_conf.py file (initially celery.py): # coding: utf-8 from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'vertNews.settings') app = Celery('vertNews') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) celery configurations in settings # Celery Configuration CELERY_TASK_ALWAYS_EAGER = False CELERY_BROKER_URL = SECRETS['celery']['broker_url'] CELERY_RESULT_BACKEND = SECRETS['celery']['result_backend'] CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = TIME_ZONE __init__.py of root app # coding: utf-8 from __future__ import absolute_import, unicode_literals from .celery_conf import app as celery_app __all__ = ['celery_app'] My tasks # coding=utf-8 from __future__ import unicode_literals, absolute_import import logging from celery.schedules import crontab from celery.task import periodic_task from .api import fetch_tweets, delete_tweets logger = logging.getLogger(__name__) @periodic_task( run_every=(crontab(minute=10, hour='0, 6, 12, 18, 23')), name="fetch_tweets_task", ignore_result=True) def fetch_tweets_task(): logger.info("Tweet download started") fetch_tweets() logger.info("Tweet download and summarization finished") … -
Forbidden Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request
I get this error when i try to access the system using http://membersite.haoyetu.com/.this the link to the server http://membersite.haoyetu.com/ this my manage.py file #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "membersite.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv) -
django - two seperate iOS apps possible?
I have an iOS app using Django as my backend. I have two types of users, business and customer, that are both using one iOS application. On my log in page I use a toggle button that allows the user to choose whether they want to log in as a customer or a client. Would it be possible to use two iOS apps, one for business and one for customers, instead of having them all in one application? I only created one Django App, if I were to separate my business and customers to two iOS apps, would it cause me to have to create two separate Django Apps as well or could I continue with my current Django set up with one application? -
In Django, how do I get all the instances of a model that have other instances of a related model attached to it with a ForeignKey field?
I'm trying to write a query that retrieves all the categories that have at least one post attached to it. In other words, I want to 'exclude' any category that doesn't have any post. These are my models for Category and Post: class Category(models.Model): title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique=True) class Post(models.Model): title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique=True) body = models.TextField() category = models.ForeignKey(Topic, blank=True, default="") This is the code I'm using in my query, currently it fetches all the categories, even if no Post is 'attached' to it: categories = Topic.objects.all() What I want is something like this: categories = Topic.objects.filter( # Only ones that have at least one Post that has it's 'category' field set to it. ) I've searched the docs and everywhere else, but I can't figure out a solution. Please let me know how this can be done. Thanks a lot! -
Django - chart won't display values correctly
The goal here is to show each bar corresponding to association and total members as displayed below: What I get is this one big block with no value. Seems that no one has the same issue here that I have been looking for. Still a newbie so appreciate all your help & guidance, folks! models.py class Member(models.Model): member_no = models.AutoField(primary_key=True) association = models.ForeignKey('Association') ... class Association(models.Model): asoc_name = models.CharField(max_length=50, null=True, blank=True) class Meta: db_table = 'Association' def __str__(self): return self.asoc_name def __unicode__(self): return self.asoc_name class AssociationSummary(Association): class Meta: proxy = True verbose_name = 'Association Summary' verbose_name_plural = 'Association Summary' admin.py @admin.register(AssociationSummary) class ChartAssociationAdmin(admin.ModelAdmin): change_list_template = 'admin/chart_association.html' def changelist_view(self, request, extra_context=None): response = super(ChartAssociationAdmin, self).changelist_view( request, extra_context=extra_context, ) try: qs = response.context_data['cl'].queryset except (AttributeError, KeyError): return response metrics = { 'association': Count('asoc_name'), 'total': Sum('member'), } response.context_data['summary'] = list( qs.values('asoc_name', 'member').annotate(**metrics) ) response.context_data['summary_total'] = dict( qs.aggregate(**metrics) ) summary_over_time = qs.values('asoc_name', 'member').annotate(total=Sum('member')) summary_range = summary_over_time.aggregate( low=Min('total'), high=Max('total'), ) high = summary_range.get('high', 0) low = summary_range.get('low', 0) response.context_data['summary_over_time'] = [{ 'asoc_name': x['asoc_name'], 'total': x['total'] or 0, 'pct':\ ((x['total'] or 0) - low) / (high - low) * 100 if high > low else 0, } for x in summary_over_time] return response chart_association.html {% extends … -
Django filter and get the whole record back when using a .values() column-based annotation
This may be a common query but I've struggled to find an answer. This answer to an earlier question gets me half-way using .annotate() and Count but I can't figure out how then to get the full record for the filtered results. I'm working with undirected networks and would like to limit the query based on a subset of target nodes. Sample model: class Edges(Model): id = models.AutoField(primary_key=True) source = models.BigIntegerField() target = models.BigIntegerField() I want to get a queryset of Edges where the .target exists within a list passed to filter. I then want to exclude any Edges where the source is not greater than a number (1 in the example below but may change). Here's the query so far (parenthesis added just for better legibility): (Edges.objects.filter(target__in=[1234,5678, 9012]) .values('source') .annotate(source_count=Count("source")) .filter(source_count__gt=1) ) This query just delivers the source and new source_count fields but I want the whole record (id, source and target) for the subset. Should I be using this as a subquery or am I missing some obvious Django-foo? -
I'ts possible access an attribute of another model via querryset?
I need to display in a page a list with the candidates for their respective averages, the candidates' scores for the calculation of the average are in another model (Evaluation), this model receives an attribute score that contains the note of that evaluation that the candidate received And a ForeignKey with the candidate, so there may be several "Evaluation" with the same candidate, I have to display all the candidates with their respective averages, however the "Candidate" template does not have access to the notes, since they are stored in the Template "Evaluation", I then thought to make a for that would take the candidates of a queryset obj.all with the candidates and make the calculation of the average according to the current result, within a loop for in "Evaluation.objects.all ( ) ", Then after passing the candidate and his average to a dictionary that was placed in an array, so far so good, it works perfectly, however I need to make when clicking the candidate the user is to redirect (Name and other information) but to use "pk" I want Querryset, not for certain dictionaries? So, what is my problem, I also tried querryset within the "Evaluation" template, but … -
How do i fix this AssertionError
self = < tests.sil_renderers.tests.test_excel_renderer.TestFieldFormatters testMethod=test_format_field_types_date_formats> def test_format_field_types_date_formats(self): # test formating date objects today = datetime.datetime.now() formatted_date = _format_field_types('date', today) year = str(today.year) month = str(today.month) day = str(today.day) self.assertEquals( "{}-{}-{}".format(year, month.zfill(2), day.zfill(2)), > formatted_date ) E AssertionError: '2017-04-03' != '3 - 4 - 2017' E - 2017-04-03 E + 3 - 4 - 2017 day = '3' formatted_date = '3 - 4 - 2017' month = '4' self = <tests.sil_renderers.tests.test_excel_renderer.TestFieldFormatters testMethod=test_format_field_types_date_formats> today = datetime.datetime(2017, 4, 3, 16, 21, 50, 540583) year = '2017' tests/sil_renderers/tests/test_excel_renderer.py:246:** -
412 (precondition failed) in Django
I have this API endpoint which signs up a user and is used by mobile apps: /mobile/v1/signup I recently migrated the app from Django 1.7 to Django 1.10. After this I started to get this strange error. If this API accessed the second time, it is returning 412 (precondition failed) error. I searched the net and as long as I understand, the following happens: The first time, the backend returns Etag in the response. Then, this Etag is then sent back to the server the second time this API is accessed. If this does not match, it returns 412. I solved this by manually setting a random value to the Etag header of the response of this API: response['Etag'] = datetime.now().timestamp() return response But I don't think this is a good solution. What is the proper way of solving this? My middleware: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'msd.middleware.RequestIdMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'apps.dashboard.middleware.DashboardMiddleware', 'api.middleware.UserAgentMiddleware', ] -
Retrofit Android Developer not working with rest_framework in Python-Django
i'm having issues getting Retrofit 2.0 to send POST requests to Python-Django. Here's my Retrofit method. public void sendNetworkRequest(User user) { //Cria instância retrofit final Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://127.0.0.1:8000/") .addConverterFactory(GsonConverterFactory.create()) .build(); UserService services = retrofit.create(UserService.class); Call<User> call = services.createAccount(user); call.enqueue(new Callback<User>() { @Override public void onResponse(Call<User> call, Response<User> response) { Toast.makeText(CadastrarActivity.this, "Você foi cadastrado com sucesso!", Toast.LENGTH_SHORT).show(); } @Override public void onFailure(Call<User> call, Throwable t) { CheckConnection checkConnection = new CheckConnection(); if (checkConnection.equals(null)){ Toast.makeText(CadastrarActivity.this, "Conecte-se a internet!", Toast.LENGTH_SHORT).show(); } else { Log.e("heurys", t.getMessage()); System.out.println(t.getStackTrace()); Toast.makeText(CadastrarActivity.this, "Algo deu errado!", Toast.LENGTH_SHORT).show(); } } }); } Here's my interface method used in the Rest call: public interface UserService { @POST("rest/cadastro") Call<User> createAccount(@Body User user); } And here's my traceback error: 04-03 12:58:43.726 18692-18692/com.example.ccyrobuosi.estudos E/heurys: Failed to connect to /127.0.0.1:8000 In advance, my Python code works just fine, i used Postman to test it, and its getting the requests properly. -
Django, Select model field type based on database backend
I want to select model field type based on database backend. So, for instance, it database backend is SQLite, then field type will be TextField. But if backend is PostgreSQL, then field type will be JSONField. Field name will be the same in all cases. Of course I understand that code processing the field may need branching too, but it is not the problem. Problem is to add field early enough, so that migrations, etc. will work. -
How to run queue in background in Django?
I need to make background process which will add post to queue and pop it to posts pool of my appication each hour. What is the best way to do this? -
i am getting error: 'for' statements should use the format 'for x in y': for c in Article_db.objects.all() article.comment_set.all
def article(request, article_id=1): return render_to_response('article.html', {'article': Article_db.objects.get(id=article_id)}) 'for' statements should use the format 'for x in y': for c in Article_db.objects.all() article.comment_set.all -
Django server side shows http 400 and Invalid HTTP_HOST header message
I am using HTTPHandler to send logging messages to a Django Web server with The following code, import logging import logging.handlers http = logging.handlers.HTTPHandler('192.168.8.100:8000', '/VideoParser/lYYDownloaderClientLog') logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d %I:%M:%S %p', handlers=[http]) logging.error('yahoo Server Exception') but The server side shows http 400 and Invalid HTTP_HOST header message like this Invalid HTTP_HOST header: '192.168.8.100:8000,192.168.8.100'. The domain name pr ovided is not valid according to RFC 1034/1035. [03/Apr/2017 21:12:42] "GET /VideoParser/lYYDownloaderClientLog?filename=log55.p y&levelno=40&relativeCreated=88.00482749938965&funcName=%3Cmodule%3E&thread=7144 &stack_info=None&module=log55&args=%28%29&exc_text=None&pathname=D%3A%5CBaiduYun Download%5C%E7%BC%96%E7%A8%8B%5CPython%5Clog55.py&levelname=ERROR&msecs=668.0548 191070557&threadName=MainThread&process=6664&name=root&lineno=34&msg=yahoo+Serve r+Exception&exc_info=None&processName=MainProcess&created=1491225161.6680548 HTT P/1.1" 400 67882 so how to fix The issue ? related code django-test\LYYDownloaderServer\VideoParser\urls.py from django.conf.urls import url from . import views app_name = 'VideoParser' urlpatterns = [ url(r'lYYDownloaderClientLog.+',views.lYYDownloaderClientLog, name='lYYDownloaderClientLog') ] django-test\LYYDownloaderServer\VideoParser\views.py def lYYDownloaderClientLog(request): print('----666666666666---', request.GET) -
Initiation call Django class based view.
This is more of a conceptual question. While learning the Django class-based view, I am wondering if it is possible to make a call to a Django view as an initiation call. I mean, after the first call, the following calls from the templates can share the instance variables created by the first one. This avoids passing variables back and forth between the template and server. -
Django makemigrations make change for 'auth.user' every time
I upgrade my system's django version from 1.6.10 to 1.8.16 for test. On before version, i use South for migration. So, I followed 'https://docs.djangoproject.com/en/1.7/topics/migrations/#upgrading-from-south' this documentation. My problem is every makemigrations are check same field, then make migration file. That field is 'auth.User' foreign key field. like user = models.ForeignKey('auth.User'). here are my screenshot for that problem. This is Sample code for that foreign key field. cancelled_by = models.ForeignKey( 'auth.User', verbose_name=_("Cancelled by"), related_name='project_cancel', blank=True, null=True ) How can i fix it? edited: This is my migration file created by makemigrations after all migration. class Migration(migrations.Migration): dependencies = [ ('meeting', '0003_meeting_proposal'), ] operations = [ migrations.AlterField( model_name='meeting', name='manager', field=models.ForeignKey(verbose_name='Manager', blank=True, to=settings.AUTH_USER_MODEL, null=True), ), ] -
Django - user is_active
This is my user authentication method: def user_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: login(request, user) return HttpResponseRedirect(reverse('index')) else: print('TEST') messages.info(request, 'Inactive user') return HttpResponseRedirect(reverse('index')) else: messages.error(request, 'Invalid username/password!') return HttpResponseRedirect(reverse('index')) else: return render(request, 'mainapp/login.html', {}) If user exists and is not active wrong message appears: messages.error(request, 'Invalid username/password!') return HttpResponseRedirect(reverse('index')) instead of: print('TEST') messages.info(request, 'Inactive user') return HttpResponseRedirect(reverse('index')) I don't have any idea what is wrong here... Any clues? -
What does it mean by object not reversible Django
I'm just trying to make a simple connection to another page using the url tag in Django. I'm getting a error of "'set' object is not reversible". After searching for a bit I've been unsuccessful in finding anything. urls.py from django.conf.urls import url from . import views APP_NAME = 'website' urlpatterns = { url(r'^$', views.admin_view, name='adminview'), url(r'^eventview/$', views.event_view, name='eventview'), } admin_view.html <!DOCTYPE html> <html lang="en" > <head> {% load static %} {% block header%} {% include 'website/header.html' %} {% endblock %} <!-- Insert custom css here --> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <!-- top navbar --> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Vivid Fireworks</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> <li><a href="{% url adminview %}">Dashboard</a></li> <li><a href="{% url eventview %}">Add Show</a></li> <li><a href="#">Settings</a></li> <li><a href="#">Profile</a></li> <li><a href="#">Help</a></li> </ul> </div> </div> </nav> I haven't ran into this problem before and it seems like it'll be a simple fix just something I'm over looking. Any help is appreciated. -
django, can I rename the application without breaking references?
I have a django directory named application. I want to change it's name to something else. However all the code references to the application namespace: from application.xxx import * What is the proper way to change the application name without breaking all the references? -
How to integrate ccavenue payment gateway in python django webapp?
How do i integrate ccavenue payment gateway to my python django webapp ? is there any django package that can help me -
django, how change table prefix globally
How can I change the DB table prefix in Django? I only found a "per table" solution withe the meta option, but I want to define it for all tables.