Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error when making migrations.
I am trying to run makemigrations on a new project but I keep getting this error: ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'login.stylista', but app 'login' isn't installed. and The field authtoken.Token.user was declared with a lazy reference to 'login.stylista', but app 'login' isn't installed. The stylista app is an old project I was working on and I have not made any references to it but I keep seeing this error. I am using django 1.10 -
Why does django create a migration file when we change the storage attribute of FileField, when the storage type is not stored in the database?
I don't want to create a migration file whenever I change the storage of the FileField. I am getting the storage class from settings.py and it is configurable. settings.py Storage = S3BotoStorage(bucket='example') models.py from django.conf import settings class myModel(models.Model): file = models.FileField(upload_to='', blank=True, storage=settings.Storage) -
Django manytomany query weird behavior
I have a following models: class Post(Model): word = TextField() subscribers = ManyToManyField(User, related_name='subscribed', through='Subscription') class Subscription(Model): post = ForeignKey(Post) subscriber = ForeignKey(User) date_subscribed = DateTimeField(default=timezone.now) class Meta: ordering = ('-date_subscribed', ) unique_together = (('post', 'subscriber')) What I want to do is to select all posts, order them by number of subscribers, and if the number of subscribers is equal, order by last date_subscribed. My input data: post1 = Post(text="post1") post2 = Post(text="post2") post3 = Post(text="post3") post4 = Post(text="post4") user1 = User(username="user1") user2 = User(username="user2") user3 = User(username="user3") user4 = User(username="user4") Subscription.objects.create(post=post1, user=user1) Subscription.objects.create(post=post2, user=user1) Subscription.objects.create(post=post3, user=user1) Subscription.objects.create(post=post3, user=user2) Subscription.objects.create(post=post3, user=user3) Subscription.objects.create(post=post3, user=user4) Subscription.objects.create(post=post4, user=user1) Subscription.objects.create(post=post4, user=user2) Subscription.objects.create(post=post4, user=user3) This query works as expected but it doesn't order by date_subscribed: Post.objects.annotate(s_count=Count('subscribers')).order_by('-s_count') When I write Post.objects.annotate(s_count=Count('subscribers')).order_by('-s_count', '-subscription__date_subscribed'), I got weird results and I don't really understand this behavior. For above data it outputs exactly 3 post4 (s_count is 1) and 1 post3 (s_count is 1) and no other posts. Where is all other data? What is behind this query? Why s_count is 1? Ans also how to order correctly by last date_subscribed? -
Django property field calculated from other property fields
Does anyone know a way in Django to calculate a field from the values of other property fields? Here's my invoice model: class Invoice(models.Model): types = [ ('customer', 'Customer'), ('supplier', 'Supplier') ] number = models.CharField(max_length=30) date_invoice = models.DateTimeField('Date', default=timezone.now()) comment = models.TextField(default=get_default_invoice_comment()) type = models.CharField(max_length=20, choices=types, default='customer') partner_id = models.ForeignKey( 'Partner', default=1, on_delete=models.CASCADE) currency_id = models.ForeignKey( 'Currency', default=1, on_delete=models.CASCADE) @property def tax_amount(self): total = 0 for line in self.invoiceline_set.all(): total += line.tax_amount return total @property def subtotal(self): total = 0.0 for line in self.invoiceline_set.all(): total += line.subtotal return total @property def total(self): return self.subtotal + self.tax_amount def __unicode__(self): return self.number The tax_amount and subtotal on the InvoiceLine model are property fields. The subtotal gets calculated fine, however the total does not as it depends on another property field (tax_amount, which also does not get calculated properly) and I guess Django does not know in what order to perform the calculations? -
Can anyone write the code for this prblem. Please ans
Q - Following you need to do, 1.User Should be able to Sign up (Name, Address, City, Country etc). 2.Use Token Authentication to call User other API after Sign In a.Get User Profil b. Update User Profile User should be able to upload and download files Calculate User occupied storage for uploaded files Hint - Use Django Auth Model. No need to create the form. Only API are needed -
I can't make a POST call from POSTMAN but can do manually- Django
I can make a POST call from Django REST Framework built-in API but,Here you can see that result I can't make such call using POSTMAN Here is POSTMAN result And also in-tab extension of POSTMAN, its showing "CSRF Failed: CSRF token missing or incorrect." I have logged in as admin also,but its not working in POSTMAN Can you tell whats wrong going Below is the Code serializers.py from rest_framework import serializers from snippets.models import Snippet from django.contrib.auth.models import * class SnippetSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Snippet fields = ('title','code',) def create(self, validated_data): return Snippet.objects.create(**validated_data) def update(self, instance, validated_data): instance.title = validated_data.get('title', instance.title) instance.code = validated_data.get('code', instance.code) instance.save() return instance Views.py from django.shortcuts import render from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from snippets.models import Snippet from rest_framework import viewsets from snippets.serializers import SnippetSerializer # Create your views here. class SnippetViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = Snippet.objects.all().order_by('title') serializer_class = SnippetSerializer Models.py from __future__ import unicode_literals from django.db import models # Create your models here. class Snippet(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=True, default='') code = models.TextField() class Meta: ordering = ('created',) -
Looping through a list of items to get their foreignkey value
I have a Feed model with the following field: class Feed(models.Model) authority=models.ForeignKey(Authority,blank=True,null=True) I have a queryset of authority called followed_authority in which I want to get the corresponding feeds from each of the authority in followed_authority The obvious thing for me is to use a for loop through followed_authority which I think its inefficient as the instanaces in following_authority and their corresponding feeds are very large.Kindly help me out -
How to make paginate retain form data while going to next page
I am using Django for creating a list of about 20 checkboxes on each page, for about N pages, using django-pagination. The checkbox data isn't stored as I traverse from a page to another. Is there any way to hook onto any of the page events, so that I could cache the data stored interim? Any pointers to such APIs or similar help would be appreciated. -
Two django ModelForms on the same page, same model, without Formset
I have two model forms on the same page. The form only has a single field, event that is selected: forms.py class RegistrationForm(forms.ModelForm): class Meta: model = Registration fields = ['event'] views.py form1 = RegistrationForm(request.POST or None, instance=user_reg1) form2 = RegistrationForm(request.POST or None, instance=user_reg2) if request.method == 'POST': if form1.is_valid() and form2.is_valid(): form1.save() form2.save() .html <form method="POST" action=""> {% csrf_token %} {{ form1 }} {{ form2 }} <input type="submit" value="Save Selections"/> </form> The forms display and populates properly, but when I change the values and hit the save button, it always saves the form2 selection to both instances. I've noticed that the DOM ids are the same, and I've been able to change the DOM id by grabbing a unique field in the Registration model (in this case, block) form.py class RegistrationForm(forms.ModelForm): class Meta: model = Registration fields = ['event'] def __init__(self, *args, **kwargs): block = kwargs.pop('block') # a unique field in the Registration model super(RegistrationForm, self).__init__(*args, **kwargs) if block: DOM_id = "event-" + str(block) self.fields['event'].widget.attrs.update({'id': DOM_id, }) This is giving the field a unique id, but both forms are still encompassed by a div with the same id: div_id_event rendered html <form method="POST" action=""> <input type='hidden' name='csrfmiddlewaretoken' value='...' /> … -
Link not firing inside Bootstrap sortable li
I have a sortable list of Django objects inside a Bootstrap tab, with links inside each element. The links, when clicked, do nothing. There's no behavior whatsoever, as if you clicked plain text. When hovering, the cursor does change, but otherwise it act like it's not a link. I've implemented this before, but with buttons instead of li's, and had no trouble with the links there. I've confirmed that the view and URLs work just fine, by placing them on other pages in normal links. There's an event listener - keydown at jquery.js:4334 - which, if killed from the developer tools, seems to be the issue. I don't know what this is, how it's started up, or what the other consequences are of killing it. Code for the tab containing the links: (the ones to benchmarks:questionremove) <div role="tabpanel" class="tab-pane" data-toggle="tab" id="questions" href="#questions"> {% csrf_token %} <script type="text/javascript" charset="utf-8"> $(document).ready(function() { // Sortable photos // jQuery and jQuery-UI are in base.html console.log('starting') var teacherid = "{{this_teacher.pk}}"; var sectionid = "{{this_section.pk}}"; var adminid = "{{this_admin.pk}}"; var benchmarkid = "{{this_benchmark.pk}}"; // using jQuery function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var … -
How to integrate swagger-ui template with DRF and Django-Rest-framwork-Swagger?
I am using Django & DRF to write REST APIs. Recently I integrated django-rest-framework-swagger to automatically populate the API docs. Today, I came across swagger-ui template [https://github.com/jensoleg/swagger-ui] and now want to replace default swagger theme with this one. What I tried already? I copied all the contents of the dist directory into /venv/lib/python2.7/site-packages/rest_framework_swagger/static/rest_framework_swagger directory. But it didn't work (UI doesn't look good at all). -
Django - Post Office and Mailgun
I'm using Django-Post-Office app to handle emails in my Django app. How do I integrate it with mailgun? Is it possible to handle emails with Django-post-office and send them via Mailgun? Is there any other service that allows sending free emails (apart from Gmail) and works with Django-post-office? I need only about 200 free emails per month. -
Best Approach To learn Django & Python along the way?
I am currently studying in Software Engineering and I have a good grip on C & C++. Recently I have been exploring Python and I have just learned the basic syntaxes of Python and how the whole thing works. I am currently reading the book Automate The Boring Stuff With Python. However, after completing this (which will be done in a few days) I want to be a full stack Django developer. (I have made a simple calculator app using django https://github.com/saiftheboss7/electricbillcalc ) But I do not understand fully how various functions in django works and how the object/class things work. (I do know them pretty well in C++). So now, what's the best way to get a good grip on both Python and Django along the way? I want to learn Python as well as Django at the same time in a way those two complement each other. Like if I am learning how classes and objects work in python, in the next lesson, I want to implement them in django by using django functions. So what is the best way for this? I have got 20 days straight and I am up to code everyday. -
mod_wsgi cannot find MySQLdb
I'm getting the following error running my project in Apache: "ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb." I don't get this error when I run the same project with "python manage.py runserver 0.0.0.0:8000" AWS Linux (CentOS) Apache (httpd) Python (not running virtualenv) Django mod_wsgi MySQL It is an AWS server. MySQL was already installed. I do not have much information about it. MySQLdb seems to be installed at /home/ec2-user/.local/lib/python2.7/site-packages. I got this running. python manage.py shell >>> import MySQLdb >>> print MySQLdb.__file__ /home/ec2-user/.local/lib/python2.7/site-packagese Apache is looking for Python packages at: "/usr/local/lib/pyhton2.7/site-packages" - see log below. Apache error_log File "/usr/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 28, in <module> raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e) ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb So I added python-mysql path to both wsgi.py and to httpd.conf -see below part of wsgi.py sys.path.append('/usr/local/www/mlpstage') sys.path.append('/home/ec2-user/.local/lib/python2.7/site_packages') Part of httpd.conf <VirtualHost *:80> ServerName www.mcyproject.com ServerAlias myproject.com DocumentRoot /usr/local/www/mlpstage/docs <Directory /usr/local/www/mlpstage/docs> AllowOverride None Require all granted </Directory> Alias /static/ /usr/local/www/mlpstage/static/ <Directory /usr/local/www/mlpstage/static> Require all granted </Directory> WSGIScriptAlias /mlp /usr/local/www/mlpstage/mlpstage/wsgi.py <Directory /usr/local/www/mlpstage/mlpstage> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> WSGIPythonPath /usr/local/www/mlpstage:/home/ec2-user/.local/lib/python2.7/site_packages Any help will be greatly appreciated. I'm not very familiar with Apache and this is my first … -
Django JSONField inside ArrayField
I have a problem inserting to a field using ArrayField with JSONField inside. models.py locations = ArrayField(JSONField(null = True,blank = True), blank=True, null = True) Insert location_arr = [{"locations" : "loc1","amount":Decimal(100.00)},{"locations" : "loc2","amount":Decimal(200.25)}] instance.locations = location_arr instance.save() When I do this, I got column "locations" is of type jsonb[] but expression is of type text[] LINE 1: ...d" = 2517, "locations" = ARRAY['{"loc... Hint: You will need to rewrite or cast the expression. So I tried to dump it using: import json location_arr = [{"locations" : "loc1","amount":Decimal(100.00)},{"locations" : "loc2","amount":Decimal(200.25)}] instance.locations = json.dumps(location_arr) instance.save() then I got this LINE 1: ...d" = 2517, "locations" = '[{"loc":... DETAIL: "[" must introduce explicitly-specified array dimensions. I am using: Django 1.9 Python 2.7 Postgres 9.4.10 psycopg2 2.6.2 -
Django not displaying correct URL after reverse
There's lots of documentation about Django and the reverse() method. I can't seem to locate my exact problem. Suppose I have two urlconfs like this: url(r'ParentLists/$', main_page, name = "main_page"), url(r'ParentLists/(?P<grade_level>.+)/$', foo, name = "foo") and the two corresponding views like this: def main_page(request): if request.method == 'POST': grade_level = request.POST['grade_picked'] return HttpResponseRedirect(reverse('foo', args = (grade_level,))) else: return render(request, 'index.html', context = {'grade_list' : grade_list}) def foo(request, grade_level): grade_level = request.POST['grade_picked'] parent_list = # get stuff from database emails = # get stuff from database return render(request, 'list.html', context = {'grade_list' : grade_list, 'parent_list' : parent_list}) Here, list.html just extends my base template index.html, which contains a drop down box with grade levels. When the user goes to /ParentLists, the main_page view renders index.html with the drop down box as it should. When the user picks a grade level from the drop down box (say 5th Grade), the template does a form submit, and main_page once again executes - but this time the POST branch runs and the HttpResponseRedirect takes the user to /ParentLists/05. This simply results in an HTML table pertaining to grade 5 being displayed below the drop down box. The problem is, when the user now selects … -
Django filter many_to_many first foreign key
Let's say we have a two models like these: Artist(models.Model): name = models.CharField(max_length=50) Track(models.Model): title = models.CharField(max_length=50) artist = models.ForeignKey(Artist, related_name='tracks') How can I filter this relationship to get the first foreign record? So I've tried something like this, but it didn't work as expected artists = Artist.objects.filter(tracks__first__title=<some-title>) Is there any way to make this work? -
Nginx looking for a different path than what is given Django static files url setting
I ran into very weird issue for which I could not find a reason. I have a django app with uWSGI as my app server and Nginx as our reverse proxy. My initial setting for the static url in Django are as below: PROJECT_DIR = "/home/ubuntu/src/myapp" MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media') MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(PROJECT_DIR, 'staticfiles') STATIC_URL = '/staticfiles/' STATICFILES_DIRS = ( os.path.join(PROJECT_DIR, 'static'), ) and what's there in the nginx conf is as below: server { listen 80; server_name stg1.myapp.com client_max_body_size 5G; # adjust to taste access_log /var/log/nginx/myapp-access.log combined; error_log /var/log/nginx/myapp-error.log; location /media { alias /home/ubuntu/src/myapp/media/; # your Django project's media files - amend as required } location /static { alias /home/ubuntu/src/myapp/staticfiles/; } location / { uwsgi_pass django; uwsgi_read_timeout 600s; uwsgi_buffering off; uwsgi_send_timeout 600s; proxy_read_timeout 600s; include /home/ubuntu/src/myapp/uwsgi_params; } } Now, when I was trying to access the server I was getting this error for the static files: 2016/12/13 20:33:03 [error] 30533#0: *194 open() "/home/ubuntu/src/myapp/staticfiles/files/css/base.css" failed (2: No such file or directory), client: 172.31.4.166, server: stg.myapp.com, request: "GET /staticfiles/css/base.css HTTP/1.1", host: "stg.myapp.com", referrer: "http://stg.myapp.com/profile/user1" Collectstatic copied all the files in the given STATIC_ROOT location. But the path actually searched was - STATIC_ROOT/files. When I changed the STATIC_ROOT to … -
Django rest - PUT requires non-specified fields to have a default = Bug?
Goal: I want to PUT a specific field to update an existing entry at id=22. I don't want to pass fields in my request that aren't getting updated. {"color":"green"} to the endpoint: /api/apple/22 where the data is initially: { "id": 22, "color": "red", "size": 4 } Problem: Fields that don't have a default throw an error, e.g. size, saying "This field is required." Code: Model class Apples(TimeStampedModel): color = models.CharField(blank=True, null=True) size = models.IntegerField() Serializer class AppleSerializer(serializers.ModelSerializer): class Meta: model = Apple fields = '__all__' View class AppleView(generics.RetrieveUpdateDestroyAPIView): queryset = Apple.objects.all() serializer_class = AppleSerializer filter_backends = (filters.DjangoFilterBackend,) permission_classes = (IsAdminUser,) Test def test_update_apple(self): url = reverse('apple-detail', kwargs={'pk': 22}) data = {"color": "green"} admin = User.objects.get(username='admin') client = APIClient() client.force_authenticate(user=admin) response = client.put(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) Thank you for your help! -
Django Post-Redirect-Get in Simple Multiplayer Game Synchronous
I have this problem, and I will explain It with an example. What I want: If there are three players playing the game, the three players share the same template ('play_game.html'), If the turn is 1, only the player 1 watches in the template an option to make a post, this post gives data to the server and modifies the turn for the next player, so he can play. The rest of the players or watch the same template that player 1 watches but because the turn is 1 (in this example) they don't watch the option to make a post, and they watch "waiting for your turn"; or they are in the template wait_turn and watch "wating for you turn" I tried a lot of ways to implement this but I couldn't This is the code: ... url(r'^play_game/(?P<played>[0-9]+)/$', views.play_game, name='play_game'), url(r'^wait_turn/(?P<pk>[0-9]+)/$', views.wait_turn, name='wait_turn'), ... the functions @login_required def play_game(request, played): player = User.objects.get(user=request.user.id) game = player.game if player.turn == game.turn: if request.method == 'POST': if game.turn < game.count_player: game.turn = game.turn + 1 else: game.turn = 1 game.save() return redirect('wait_turn', pk=player.pk) turn = game.turn context = { 'player' : player, 'turn' : turn } return render(request,'play_game.html', context) @login_required def … -
Use Check Box and Dropdown to Change Values
I am working on a Django project where the user submits a link, then an admin/moderator has the ability to accept or decline the link. In my models there is an attribute called status that is Submitted by default. What I hope to accomplish is an admin page where a moderator can look at all the submitted links and click on a checkbox and then select a value form a dropdown list that will change status to Approved or Denied, similar to the steps you wold take to delete an entry in Django admin. Here is my models.py: class WebPage(models.Model): STATUS_CHOICES = ( ('Submitted', 'Submitted'), ('Approved', 'Approved'), ('Denied', 'Denied'), ('Scraped', 'Scraped'), ) url = models.URLField() title = models.CharField(max_length=250, null=True, blank=True) stack = models.ForeignKey(Stack) submitter = models.ForeignKey(User) status = models.CharField(max_length=50, choices=STATUS_CHOICES, default='Submitted') my views.py: def admin_tools(request, stack_url): context_dict = {} stack = Stack.objects.get(url=stack_url) context_dict['stack'] = stack new_links_list = WebPage.objects.filter(stack=stack, status="Submitted") context_dict['new_links_list'] = new_links_list return render(request, 'stack/admin_page.html', context_dict) and finally my html: <table class="table table-bordered"> <tr> <th></th> <th>Title</th> <th>Submission Type</th> <th>Submitted by</th> </tr> {% for link in new_links_list %} <tr> <td><input type="checkbox"></td> <td><a href="{{ link.url }}"> {{ link.title }} </a></td> <td>{{ link.link_type }}</td> <td>{{ link.submitter }}</td> </tr> {% endfor %} </table> Any … -
How to Integrate OpenFace with Django?
I have a school project and it involves face recognition and not just face detection. I've been using Django for a while, like a year, so I'd like to integrate OpenFace with Django. The reason why OpenFace is because it uses python, and that it is one of the most accurate in face recognition I've seen. So now I'm asking how to do integrate it to Django. Thanks! -
Django, detect if model field is inherited
I'd like to check if a model field is inherited, similar to Field.is_relation. Is there a way to tell? I have a model that inherits from MPTTModel and I want a list of the attributes defined directly in the model but not in MPTTModel. E.g.: # models.py class ACoolModel(MPTTModel): name = CharField(max_length=128) Then, something like: [f.attname for f in ACoolModel._meta.get_fields(False)] Gives back the fields from MPTTModel as well: ['id', 'name', 'lft', 'rght', 'tree_id', 'level'] But I want it to return: ['id', 'name'] -
django parameter gets none even on redirect with parameter
I have the following view that I want to only stay in the current view if it hasn't been redirected. def surveys_view(request, survey=None): if survey != 'survey1': return redirect('matching:surveys', survey='survey1') The problem is that the survey variable is None every time causing infinite redirects. I would think that after the redirect, the survey value would be set to 'survey1'. How can I have the survey parameter set to 'survey1' instead of None? -
Django View on Ajax call
I'm creating a catalogue page. On this page I want to allow user to filter the products. So I created a sidebar with checkboxes and input texts. I would like that every time the user changes the filter parameters, the catalogue is updated. this is my code: html for sidebar (filter): <h3>Filtri:</h3> <b>Marca:</b><br> {% for marca in marche %} <input type="checkbox" title="{{ marca.nome }}" value="{{ marca.nome }}" name="marca" class="marca" onclick="filtra()"> {{ marca.nome }} <br> {% empty %} <p>Nessuna Marca è ancora stata inserita.</p> {% endfor %} <br> <b>Portata:</b> <br> Maggiore di <input type="text" title="portata" name="portata" id="portata" class="textbox-filtro" maxlength="4" onblur="filtra()"> kg <br><br> <b>Sollevamento:</b> <br> Maggiore di <input type="text" title="sollevamento" id="sollevamento" class="textbox-filtro" maxlength="4" onblur="filtra()"> mt <br><br> <b>Trazione:</b><br> {% for tra in trazione %} <input type="checkbox" title="{{ tra.trazione }}" value="{{ tra.trazione }}" id="{{ tra.trazione }}" class="trazione" onclick="filtra()"> {{ tra.trazione }} <br> {% empty %} <p>Nessuna Trazione è ancora stata inserita</p> {% endfor %} <br> <b>Idroguida:</b><br> {% for idro in idroguida %} <input type="checkbox" title="{{ idro.idroguida }}" value="{{ idro.idroguida }}" id="{{ idro.idroguida }}" class="idroguida" onclick="filtra()"> {{ idro.idroguida }} <br> {% empty %} <p>Nessuna Idroguida è ancora stata inderita</p> {% endfor %} As you can see, I've 5 filter groups: Marca (brand), Portata (carrying capacity), …