Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Many-to-one relationships
For my question, I´ll be using Examples of Django documentation. My problem is that I would like to click a Reporter name and then change webpage to get the list of all articles. This is the models.py from django.db import models class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() def __str__(self): # __unicode__ on Python 2 return "%s %s" % (self.first_name, self.last_name) class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) def __str__(self): # __unicode__ on Python 2 return self.headline class Meta: ordering = ('headline',) How can I change one model to other useing Many-to-one relationship with Class-based views. https://docs.djangoproject.com/en/1.11/topics/db/examples/many_to_one/ Thanks in advance -
Django admin inlines with different readonly fields
Say we have model inlines in Django admin. How can we make some fields(of inline) readonly if inline object exists but editable for new instances? For example if model has related comments, we wont let existing comments to be editable, but possible to create new (from inline admin). -
Django-Rest-Framework - nested objects and serializers, how to?
I'm using DRF for the first time. I've been reading the documentation pages but no clue on how to do this. I have two models, the AdPrice Model make reference to the Ad Model. I need to list the various prices for an Ad. My question is: How can I get a list of Ads like this? [ { "title": "Some long title for Ad1", "name": "Name Ad1", "prices": { { "name": "price now", "price": 200 }, { "name": "price later", "price": 300 } } }, ] models.py class Ad(models.Model): title = models.CharField(max_length=250) name = models.CharField(max_length=100) def __str__(self): return self.name class AdPrice(models.Model): ad = models.ForeignKey(Ad) name = models.CharField(max_length=50) price = models.DecimalField(max_digits=6, decimal_places=2) def __str__(self): return self.name serializers.py class AdPriceSerializer(serializers.Serializer): name = serializers.CharField(max_length=50) price = serializers.DecimalField(max_digits=6, decimal_places=2) class Meta: model = AdPrice class AdSerializer(serializers.Serializer): title = serializers.CharField(max_length=250) name = serializers.CharField(max_length=100) prices = AdPriceSerializer(many=True) views.py class AdViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = Ad.objects.all().order_by('-date_inserted') serializer_class = AdSerializer When I try the code above I got this error: AttributeError at /ads/ Got AttributeError when attempting to get a value for field `prices` on serializer `AdSerializer`. The serializer field might be named incorrectly and not match … -
Searching multiple fields in Django for loop
I have a couple form fields I need to format differently and am trying to use a IF statement to find the fields when rendered, but doesn't seem to be working as the documentation suggests. I want to format "Country" and "State" differently, but the code doesn't like what I'm trying. {% for field in customerfields %} {% if field.name != 'country' or 'state' %} {{ field.label.upper }} <div class="FormRow"> {{ field }} </div> {% else %} <div class="FormRow"> <div class="StyledSelect"> {{ field }} </div> </div> {% endif%} {% endfor %} How do I search for more than one field? Is there a better way to do this? -
Cannot define model in django
I am trying to build my first django app using the most common posts as an test. Unfortunately the server keeps returning errors such as Postmodel admin not defined. I have tried migrating the new changes but this doesnt work, as well as modifying the views, but it seems i need to explicitly define this model. Could someone point me in the right direction Heres how my admin.py looks like from django.contrib import admin Register your models here. from .models import posts import views admin.autodiscover() class PostsModelAdmin(admin.ModelAdmin): list_display = ('title', 'updated', 'timestamp') list_display_links = ('updated') list_editable = ('title') list_filter = ('updated', 'timestamp') search_fields = ("title", 'content') class Meta: model = posts admin.site.register(posts) admin.site.register(PostModelAdmin) -
'python -m django' gives conflicting messages in virtualenv
I created a virtualenv: virtualenv --python=/usr/local/bin/python2.7 workoutpy2.7 I'm working on a workout diary web app, hence that name. Then I installed django nonrel in it: pip install git+https://github.com/django-nonrel/django@nonrel-1.5 and then djangotoolbox for django nonrel: pip install git+https://github.com/django-nonrel/djangotoolbox and then the mongodb engine: pip install git+https://github.com/django-nonrel/mongodb-engine I then assumed that django was installed in my virtualenv. So I typed: python -m django and got the following output: /Users/sahandzarrinkoub/Documents/Programming/Web/Django/workoutpy2.7/bin/python: No module named django.__main__; 'django' is a package and cannot be directly executed What does this mean? For the record, the same thing happens with ANY package I install in this way. Just have a look at this: (workoutpy2.7) Sahands-MacBook-Pro:workoutpy2.7 sahandzarrinkoub$ pip install pymongo Requirement already satisfied: pymongo in ./lib/python2.7/site-packages (workoutpy2.7) Sahands-MacBook-Pro:workoutpy2.7 sahandzarrinkoub$ python -m pymongo /Users/sahandzarrinkoub/Documents/Programming/Web/Django/workoutpy2.7/bin/python: No module named pymongo.__main__; 'pymongo' is a package and cannot be directly executed Thankful for any help. -
Python sports game outcome algorithm
I would like to create an algorithm to generate a score for both teams in a game using both an element of random, and the teams overall rating. So far I have something similar to the following. # determine score home_overall = 78 away_overall = 85 home_score = numpy.random.choice(range(4), p=[.2, .4, .3, .1]) away_score = numpy.random.choice(range(4), p=[.2, .4, .3, .1]) I'm unsure how to factor in the teams overall rating without it being a direct correlation to the outcome. What I DON'T want is to take the score and just multiply it by the teams overall. Ideally I'd like to include more granular factors in the future instead of just overall, but that may be something to tackle another day. -
python app not starting in visual studio
I have created django python app, and when I press F5 , it pops up a python shell which says Available subcommands: [auth] changepassword createsuperuser [django] check compilemessages createcachetable dbshell diffsettings dumpdata flush inspectdb loaddata makemessages makemigrations migrate runfcgi shell showmigrations sql sqlall sqlclear sqlcustom sqldropindexes sqlflush sqlindexes sqlmigrate sqlsequencereset squashmigrations startapp startproject syncdb test testserver validate [sessions] clearsessions [staticfiles] collectstatic findstatic runserver Press any key to continue . . . But it does not open any browser and app is not running, when I hit any key , it just stops the app. I am wondering what is the issue. Weird thing is few days ago this app was working fine and I didn't do anything after that. -
Anybody get django cookiecutter to work with anaconda instead of virtualenv?
Just when I think I'm starting to get a handle with django I start reading Two Scoops Of Django where they advise to use Cookiecutter instead of the regular django-admin startproject. The authors of Two Scoops are big on virtualenv. I've been using Anaconda because everywhere says it's better than virtualenv. I'm tempted to get rid of anaconda and just use virtualenv to try to get this to work, but figured I'd ask here first. Anybody know how to get cookiecutter to work with Anaconda??? -
Django Collectstatic Suspicious File operation
I am trying to run collectstatic on heroku. When I got this error: remote: 'component ({})'.format(final_path, base_path)) remote: django.core.exceptions.SuspiciousFileOperation: The joined path (/tmp/build_4652acfe079723bc273763513a187201/fonts/glyphicons-halflings-regular.eot) is located outside of the base path component (/tmp/build_4652acfe079723bc273763513a187201/staticfiles) I thought perhaps I had missed something with collectstatic on my end, so I ran it locally, and got the exact same error. Then I went looking. I found: /home/malikarumi/Projects/aishah/jamf35/staticfiles/bootstrap/fonts/glyphicons-halflings-regular.eot and /home/malikarumi/Projects/aishah/jamf35/static/bootstrap/fonts/glyphicons-halflings-regular.eot My settings: STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static/bootstrap/fonts/'), There is a ticket out there, but it seems to be about paths, and I see nothing wrong with my paths, https://code.djangoproject.com/ticket/27201 Another one deals with files, and might be closer to my issue, because it has to do with created tmp files, but I really can't tell: https://code.djangoproject.com/ticket/26644 I should note that I also looked at Django: The joined path is located outside of the base path component, Django: How to allow a Suspicious File Operation / copy a file, and Django | joined path is located outside of the base path component {% static img.thumbnail.url %}, Error 400 with whitenoise, but they seem to be more about MEDIA ROOT issues. I'm not sure what the fix is, here. Please advise. Thanks. -
Django on mod_wsgi syntaxError
I installed Django 1.11.5 with Virtualenv on mod_wsgi. python version is 2.7.13. I get this error in /var/log/httpd/error_log: [Wed Sep 13 16:41:00 2017] [error] [client 5.125.70.26] mod_wsgi (pid=9606): Target WSGI script '/var/www/html/memit/memit/wsgi.py' cannot be loaded as Python module. [Wed Sep 13 16:41:00 2017] [error] [client 5.125.70.26] mod_wsgi (pid=9606): Exception occurred processing WSGI script '/var/www/html/memit/memit/wsgi.py'. [Wed Sep 13 16:41:00 2017] [error] [client 5.125.70.26] Traceback (most recent call last): [Wed Sep 13 16:41:00 2017] [error] [client 5.125.70.26] File "/var/www/html/memit/memit/wsgi.py", line 13, in <module> [Wed Sep 13 16:41:00 2017] [error] [client 5.125.70.26] from django.core.wsgi import get_wsgi_application [Wed Sep 13 16:41:00 2017] [error] [client 5.125.70.26] File "/var/www/html/memit/env/lib/python2.7/site-packages/django/__init__.py", line 3, in <module> [Wed Sep 13 16:41:00 2017] [error] [client 5.125.70.26] from django.utils.version import get_version [Wed Sep 13 16:41:00 2017] [error] [client 5.125.70.26] File "/var/www/html/memit/env/lib/python2.7/site-packages/django/utils/version.py", line 7, in <module> [Wed Sep 13 16:41:00 2017] [error] [client 5.125.70.26] from django.utils.lru_cache import lru_cache [Wed Sep 13 16:41:00 2017] [error] [client 5.125.70.26] File "/var/www/html/memit/env/lib/python2.7/site-packages/django/utils/lru_cache.py", line 28 [Wed Sep 13 16:41:00 2017] [error] [client 5.125.70.26] fasttypes = {int, str, frozenset, type(None)}, [Wed Sep 13 16:41:00 2017] [error] [client 5.125.70.26] ^ [Wed Sep 13 16:41:00 2017] [error] [client 5.125.70.26] SyntaxError: invalid syntax And My Apache virtual host is: <VirtualHost *:80> ServerName … -
Adding a button to Wagtail Dashboard
Is it possible to add a button on the top panel as shown in the picture? I did't find anything in Google here. -
Django Search Query comparing votes and post age with Annotate
I trying to make a django query to get posts order by VOTES - POST AGE. Example: Normal Posts 1 - Hello World (10 votes) (Posted today) 2 - Stackoverflow ( 12 votes) (Posted 2 days ago) 3 - StackExchange ( 30 votes ) (Posted 19 days ago) So when I filter query by annotate, I want this: 1 - StackExchange ( 30 votes - 19 days ago = 11 points) 2 - Hello World ( 10 votes - 0 days ago = 10 points) 3 - Stackoverflow ( 12 votes - 2 days ago = 10 points) What I try: class DiffDays(Func): function = 'DATEDIFF' template = "%(function)s(%(expressions)s)" class CastDate(Func): function = 'DATE_FORMAT' template = "%(function)s(%(expressions)s, '%%%%Y-%%%%m-%%%%d')" list_posts = posts.extra(select={'pub_date': "DATE_FORMAT(pub_date,'%%%%Y-%%%%m-%%%%d')"}).annotate(diff_days=DiffDays(CastDate(today), F('pub_date')), output_field = DecimalField()).annotate(days_votes=ExpressionWrapper(F('n_votes') - F('diff_days'), output_field=IntegerField())).order_by('days_votes') but I'm getting: 'IntegerField' object has no attribute 'resolve_expression' -
Card-flip functionality in Django Quiz website.
I am building a quiz web app in Django, using tomwalker's quiz app? I would like to present the questions on a card, when a user answers the question the card shall flip and show the explanation of question and correct answer. I am new to Django. This is technically my first project.I am not sure how will i populate backside of card with answer explanation, after the user submits he answer. -
Get column data based on foreign key and manytomanyfield in django admin
I am new in Django. I have the following models in Django Category id category_name 1 A 2 B Module (category_id is the foreignkey) id module_name category_id 1 X 1 2 Y 2 category_user (user_id is ManyToManyField with category_id) id category_id user_id 1 1 23 2 2 23 So I want to display data X & Y from module in admin category edit page if that category id 1 & 2 is assigned to user 23. admin.py class categoryAdmin(admin.ModelAdmin): list_display = ('category_name','category_desc') filter_horizontal = ('user',) readonly_fields = ('allowed_module_names',) def allowed_module_names(self, instance): modules = [] module_names = instance.category.values_list("module_name") print(module_names) The query returns blank. Any help is highly appreciated. Thanks in advance. -
Django - access class attributes of a class-based view in middleware
I have a couple of views and each of them must be accesed by no more than one user at a time. Therefore I use a locking service for this. My idea is as follows: - Declare each view like this class DummyView(View): lock = Lock() def dispatch(self, request, *args, **kwargs): ... - In a middleware, do something like this class Middleware: ... def __call__(self, request): # lock = view.get_lock_if_it_has_one (this is what I need help with) lock.acquire() response = self.get_response(request) lock.release() return response How can I access the lock attribute of the view as described? -
Passing Unique Variable when Sending E-Mail with Django
In my Django project I have leads which belong to an organization. One of my views filters these leads by organization and then e-mails them a message. This message is in the form of an html template. Currently this is how I do it: # FIRST: get a list of all the emails leads_email = [] leads = Lead.objects.filter(organization=organization) for lead in leads: if lead.email != None: leads_email.append(lead.email) # SECOND: Django email functions msg = EmailMessage(subject, get_template('email_templates/campaign_email.html').render( { 'message': message, } ), from_email, bcc=to_list) msg.content_subtype = "html" msg.send() However each lead has a unique code associated with them, this field is found under lead.code. I would like to include this code in the email. For example if test@mail.com's unique code is "test123", then I want to include that in the email to test@mail.com alone. I am currently doing this by passing though a variable called message, however this is not unique and every lead gets the same thing. Any idea on how I can accomplish this? Thanks -
How to create a local variable in a html template in django project?
I am a beginner to python and django. Here I am trying to build a website. I have created a class named cluster which actually mean a town or city. As a subclass I have created schools for cluster. Schools have a field school_strength to get strength for each school. Now I have to display the total strength of all the schools that belong to each cluster. This is how I am trying to do that in html template for cluster details by creating a local variable strength to calculate sum from all schools. <div class="col-sm-4 col-md-3"> <div class="panel panel-default"> <div class="panel-body"> <a href="{% url 'music:cluster_detail' state.id region.id cluster.id %}"> {% if cluster.cluster_logo %} <img src="{{ cluster.cluster_logo.url }}" class="img-responsive"> {% else %} <h3>No image to display</h3> {% endif %} </a> <h2>{{ cluster.cluster_name }}</h2> <h4>{{ cluster.cluster_coordinator }}</h4> <h4>{{ cluster.cco_number }}</h4> <h4>{{ cluster.cco_email }}</h4> {% for school in cluster.school_set.all %} {% strength = strength + school.school_strength %} {% endfor %} <h4>{{ strength }}</h4> </div> </div> </div> Please help me in this. -
django web app deployment gunicorn + aws ECS issue
I have working django REST API docker image with following dependencies python 3.5.2, django 1.10.6, djangorestframework 3.6.2, gevent 1.2.2 In my dockerfile, port 5000 is exposed docker command: /usr/local/bin/gunicorn --log-level=DEBUG --worker-class gevent --timeout=300 config.wsgi -w 4 -b :5000 In ECS task definition 5000 container port is forwarded to port 80 of the host. the security group has inbound rule allowing everyone at port 80. When I ran the ECS task with this ECS task definition, following are the application logs, which seems fine. [2017-09-13 16:45:34 +0000] [9] [INFO] Starting gunicorn 19.6.0 [2017-09-13 16:45:34 +0000] [9] [INFO] Listening at: http://0.0.0.0:5000 (9) [2017-09-13 16:45:34 +0000] [9] [INFO] Using worker: gevent [2017-09-13 16:45:34 +0000] [12] [INFO] Booting worker with pid: 12 [2017-09-13 16:45:34 +0000] [13] [INFO] Booting worker with pid: 13 [2017-09-13 16:45:35 +0000] [15] [INFO] Booting worker with pid: 15 [2017-09-13 16:45:35 +0000] [16] [INFO] Booting worker with pid: 16 but I am unable to access the service endpoints using the EC2 instance's public IP/Public DNS address. I tried to get into the running container and curl the application url curl localhost:5000 following are the logs I see (the connections are closed) [2017-09-13 17:42:42 +0000] [14] [DEBUG] GET / [2017-09-13 17:42:42 +0000] … -
Build a list of values from queryset list (pk__in) in special order
i have a model with rating, the results of a filter query must be in a special order for charity (comparing ratings for trainee's) but I can't find the right way to do it. (ok I'm new to Django and python ;) class Bewertung(models.Model): auffassung = models.PositiveSmallIntegerField() interesse = models.PositiveSmallIntegerField() arbeitsabw = models.PositiveSmallIntegerField() aufmerksamkeit = models.PositiveSmallIntegerField() arbeitsgenauigkeit = models.PositiveSmallIntegerField() verhalten = models.PositiveSmallIntegerField() ausb_sach = models.PositiveSmallIntegerField(null=True, blank=True) ausb_fuehr = models.PositiveSmallIntegerField(null=True, blank=True) the query: qs = Bewertung.objects.filter(pk__in=pk_list) i want to compare the integer values in a multi bar chart e.g. auffassung_from_pk(1,2,3) interesse_from_pk(1,2,3) .. n but every try ends in a list with a lot of unordered values (Auffassung_from_pk(1), interesse_from_pk(1), Auffassung_from_pk(2) ..) I can't find a way to solve it nice and efficient in an python way. so I need a little help, can you help? thanks! -
Class based views: How to access variable from form_valid() in success_url()
I have a simple email form that works fine but I want to access recipient in success_url() so I can have a simple "email has been sent to recipient" message in the success template. class FullEmailView(FormView, MyCustomMixin): form_class = EmailForm template_name = 'my_app/email_form.html' def form_valid(self, form, **kwargs): x = MyModel.objects.get(pk=self.kwargs['pk']) recipient = form.cleaned_data.get('email_address') subject = "My Email Subject" sender = "me@myemail.com>" html_message = render_to_string('my_app/email.html', { 'x': x, 'recipient': recipient, }) message = render_to_string('my_app/email.html') send_mail( subject, message, sender, [recipient], html_message = html_message ) return super(FullEmailView, self).form_valid(form) def get_success_url(self, form, **kwargs): x = MyModel.objects.get(pk=self.kwargs['pk']) recipient = #???? <<<--- what do I put here to access recipient from from_valid()? return super(FullEmailView, self).reverse_lazy('email_sent', self, kwargs={"pk": x.pk}) -
How to access multiple image URL from one app to another app in django
I have two apps in my project. They are: Blog app Accounts app In accounts app contains user profiles like Images, Bio, DOB etc, In blog app each user has their own blog page and Each page must have comments so any user can comment any blog. In comments section, it shows username and his unique profile URL.Now my problem is I can't load their profile images. models.py class comments(models.Model): blogger= models.ForeignKey(blog,on_delete=models.CASCADE) user = models.ForeignKey(User) created = models.DateTimeField(auto_now_add=True) comment = models.TextField() def get_absolute_url(self): return reverse('blog:comments',args = [ self.id]) views.py commentz = comments.objects.filter(blogger= id).all().order_by('-created')[:10] for pic in commentz: image = UserProfile.objects.filter(user = pic.user) I know this is insane :-/ -
AWS ECS Docker task definition Exit Code 0 Working directory
I've been working to translate my docker compose file into a ecs task definition. Im not sure what exit code 0 refers to nor do I see anything useful when I launch the agent shell in the container. This is the task as it stands. my Django container should be launch using unicorn on port 8000, then nginx should reverse proxy and use port 80 for the frontend. can anyone spot anything or point me in the right direction to debug? Thanks { "requiresAttributes": [ { "value": null, "name": "com.amazonaws.ecs.capability.docker-remote-api.1.17", "targetId": null, "targetType": null }, { "value": null, "name": "com.amazonaws.ecs.capability.ecr-auth", "targetId": null, "targetType": null } ], "taskDefinitionArn": "arn:aws:ecs:eu-west-1:********:task-definition/it-app-task:7", "networkMode": "bridge", "status": "ACTIVE", "revision": 7, "taskRoleArn": null, "containerDefinitions": [ { "volumesFrom": [], "memory": 300, "extraHosts": null, "dnsServers": null, "disableNetworking": null, "dnsSearchDomains": null, "portMappings": [ { "hostPort": 8000, "containerPort": 8000, "protocol": "tcp" } ], "hostname": null, "essential": true, "entryPoint": null, "mountPoints": [], "name": "it-app", "ulimits": null, "dockerSecurityOptions": null, "environment": [], "links": null, "workingDirectory": "/itapp", "readonlyRootFilesystem": null, "image": "*******.dkr.ecr.eu-west-1.amazonaws.com/itapp", "command": [ "bash", "-c", "", "python manage.py collectstatic --noinput && python manage.py makemigrations && python manage.py migrate && gunicorn itapp.wsgi -b 0.0.0.0:8000" ], "user": null, "dockerLabels": null, "logConfiguration": null, "cpu": 0, "privileged": null, "memoryReservation": … -
Displaying the local time for datetime attribute of a model object in Django
I'm trying to make it so the datetime field attribute of a model object is displayed in the template as the local time of the timezone of the current user. The default timezone in my settings is UTC. Here is an example model: models.py class Basic(models.Model): name = models.CharField(max_length=128) created_at = models.DateTimeField(auto_now_add=True The data I want to display is in a table made with django-tables2. However, I already tried two methods and both of them did not work: tables.py attempt 1: class ShipperDataFileDocumentTable(tables.Table): created_at = tables.TemplateColumn(''' {% load tz %} {% localtime on %} {{ record.created_at }} {% endlocaltime %} ''') class Meta: model = Basic fields = ('name', 'created_at') tables.py attempt 2: class ShipperDataFileDocumentTable(tables.Table): created_at = tables.TemplateColumn(''' {% load tz %} {{ record.created_at|localtime }} ''') class Meta: model = Basic fields = ('name', 'created_at') Both of these methods ended up not changing the time at all. For example, I made an object at 12:00 PM. Normally, the template would display it as 4:00 PM in UTC. However, even with those edits, it still displayed the time as 4:00 PM. I'm not sure what I'm doing wrong. -
How can Django recognize language changes in a multilingual web page implemented in Django?
I have already implemented a web page in English using Django. I now have a question when I'm trying to create a web page in Chinese. Pages in Chinese will be separated by prefix(/ch/). I plan to implement a button to change the language, but the question is how Django remembers the changed page. Assuming my domain is 'domain.com', if the language is set to Chinese via the button I would like to have 'domain.com/ch' open when users access 'domain.com'. However, clicking on a button does not seem to be able to control the urlpatterns of Django(urls.py), and it seems necessary to store the variable corresponding to language in javascript. I would appreciate your advice.