Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImportError: No module named django_extensions
I am completely new to python as well as to django. I got a sample django rest project and i am trying to run python manage.py makemigrations and gets an error ImportError: No module named django_extensions How could i solve this? I am running it on a virtualenv -
blank page or KeyError in preview Wagtail 1.10.1
I just upgraded to Wagtail 1.10.1 and the preview shows only a blank page. When I force the preview by appending preview/ to the edit URL, then I get a server error. It all works just fine on my development and staging sites, so I also need some help tracking down where the error might be. Internal Server Error: /admin/pages/81/edit/preview/ KeyError at /admin/pages/81/edit/preview/ 'wagtail-preview-81' Django Version: 1.11.1 Python Executable: /usr/local/bin/uwsgi Python Version: 3.5.2 I've been doing only minimal upgrades for a few months, so it's possible I missed something in a previous upgrade that used to work but that now I need to fix (although why it would work in the dev and staging sites but not the real one puzzles me); any suggestions would be welcome. -
Django ModelChoiceField, validation for dynamic queryset
I have this current form: class PersonForm(forms.Form): article = forms.CharField(required=False) workshop = forms.ModelChoiceField(queryset=Program.objects.none(), empty_label="----", required=False, label='Atelier') def __init__(self, *args, **kwargs): super(PersonForm, self).__init__(*args, **kwargs) article = self.initial.get('article', None) if article: a = Article.objects.get(pk=article) if a.workshop: self.fields['workshop'].queryset = Program.objects.filter(event=a.event, workshop=True) self.fields['workshop'].required = True self.helper.layout.insert(4, Row1Field('workshop',)) The queryset used to retrieve all the workshops is dynamic, so the queryset attribute inside the ModelChoiceField is set to Program.objects.none(), and the dynamic queryset is done inside the form's __init__ method Everything is working fine: all the values displayed for workshop inside the select are ok. But when I post the form, there is a validation error: 'Select a valid choice. This choice is not among available choices.' Is there something I'm missing? -
How can I change the migration order for an app to run after the other apps?
I'm using ModelSerealizer to generate the api of my project and I have a home = CasaLegislativa.objects.first () attribute as described in the code below: `` ` Class SessionPlenariaSerializer (serializers.ModelSerializer): ... Home = HouseLegislativa.objects.first () ... `` ` When I run python manage.py migrate I get the following error: ` Django.db.utils.ProgrammingError: relation "base_casalegislativa" does not exist ` This error occurs because the call to the CasaLegislativa.objects.first () method of the SessionSingleClassSerializer class is called before the creation of the table for the ClassLogic class in the database. The app 'api' has no Model and no migration (I can not use dependency on other migrations), but it is checked first because it comes first alphabetically. How can I change the order of the migration so that this app 'api' runs after the others? -
Refresh on adding many2many in from inline
I have inline with many2many field in it. After adding new record using add button and popup window for manytomany field, newly added record is not shown in other inlines in the page. Also, if I want to add new inline after it, newly added manytomany record does not exist until page is refreshed. Example: class Target(models.Model): name = models.TextField() class Task(models.Model): targets = models.ManyToManyField(Target) section = models.ForeigKey(Section) class Section(models.Model): name = models.TextField() And in admin: class TaskInline(admin.StackedInline): model = Task class SectionAdmin(admin.ModelAdmin): inlines = (TaskInline,) If I add new Target from TaskInline form, newly added target cannot be seen in other Task inline forms, nor if I add new Task inline. Is there a way to refresh the page on Target save, or is there any better solution? -
How to factor a very big (10k x 20k) table to enable fast query of a subset of rows and columns in SQL database
I am using Django, and I've factored the big table into small tables. Here is my attempt: class Instance(models.Model): name = models.CharField(max_length=20) class Feature(models.Model): name = models.CharField(max_length=20) class Value(models.Model): instance = models.ForeignKey(Instance) feature = models.ForeignKey(Feature) value = models.FloatField() The most frequent query is to select a small subset of rows (a few hundreds of Instances) and columns (a few dozens of Features) from the big table. I find myself selecting the Features and the samples, then looping around them to get all the corresponding Values, which ends up hitting the database dozens of times, which appears to be very inefficient. I wonder if there is a common strategy for factoring giant table and enable fast query of a subset of rows and columns -
allowed hosts when deploying django web application on heroku
I have developed a django web application for my project and deployed it on heroku, well almost. After pushing the site through git push heroku master command, I opened the app from heroku dashboard it gives me the error Blockquote Request Method: GET Request URL: https://smartagri.herokuapp.com/ Using the URLconf defined in smartagri.urls, Django tried these URL patterns, in this order: ^smartagri/ ^admin/ The empty path didn't match any of these. Blockquote Below are the associated files. I don't exactly get what I am doing wrong with the urls or how are they redirecting? Should we add .herokoapp after the address but that doesn't makes sense to me. Any help would be really appreciated. smartagri/urls.py: urlpatterns = [ url(r'^smartagri/', include('polls.urls')), url(r'^admin/', admin.site.urls), ] polls/urls.py: app_name = 'smartagri' urlpatterns = [ url(r'^$', views.intropage, name='intropage'), url(r'^accounts/', include('django.contrib.auth.urls')), url(r'^history/([a-zA-Z0-9-_]+)/$', views.history,name='history'), url(r'^about/$', views.AboutView.as_view()), ] -
bootstrap-datetimepicker inside django template , selected date not inserted into the Input field
<div class="modal fade" id="squarespaceModal" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span> </button> <h3 class="modal-title" id="lineModalLabel">Schedule Message</h3> </div> <div class="modal-body"> <!-- content goes here --> <form> <div class="form-group"> <label for="dtp_schedule" class="col-md-2 control- label">Publish on :</label> <div class="input-group date form_datetime col-md-5" data- date-format="yyyy-mm-dd hh:ii:ss" data-link- field="dtp_schedule"> <input class="form-control" size="16" type="text" value="" readonly> <span class="input-group-addon"><span class="glyphicon glyphicon-remove"></span></span> <span class="input-group-addon"><span class="glyphicon glyphicon-th"></span></span> <input type="hidden" id="dt_now" value="{% now 'Y-m-d H:i' %}"> </div> </div> <div class="form-group"> <span id="txt_error_schedule" class="alert alert-danger hide text-center col-md-12 col-xs-12">Please select a date.</span> </div> </form> The form inside the modal-body where the datapicker is used.eventhough the datepicker window pops up the selected date time is not getting inserted into the field, and whenever the the "Schedule" button is clicked it shows please select a date error -
Django template language shortens words
I would like to display the language(s) a user chose for his user profile. Everything is working I just can't display the full language name. So when I write {{user.userprofile.language}} the html Output is "English, Spanish, French" but when I write {{user.userprofile.language.0}} I get "en" instead of "English". Anybody know how to display the full Value? -
django search field perfoming a request from another site
How can i use django to create a search field that will be able to perform a request from another website and render back some information from the site. for example if i submit this form number (PGA1512194112) the app will be able to go to https://mis.unijos.edu.ng/pg/admissions/, search for PGA1512194112 and return back PGA1512194112's fullname, form number, faculty, department, programme and session. -
Incorrect escaping in Django SQL query
Here's the query I'm trying to run: MyModel.objects.filter(created__lt=functions.TruncDay(Value(timezone.now(), output_field=DateTimeField()))) It translates to: SELECT <field-list> FROM "mymodel" WHERE "mymodel"."created" < (DATE_TRUNC('day', %%s AT TIME ZONE %s)) before Django performs parameter substitution. Note that the first %s has been escaped to %%s. This causes the parameter substitution to throw an exception. Is this intended behaviour or a bug? -
Django block access to a detailview based on field
I have a detailView/template that has a confidential field (Boolean) and I want the detail page to be only accessible by staff users (or higher). I have currently made it work by adding the following to my template: {% if enzymes.confidential = True %} {% if user.is_staff %} # confidential data is listed here {% else %} <p>You do not have access to this page</p> {% endif %} {% else %} # non confidential data is listed here {% endif %} However, I want to know if I can't just apply a filter to my view? The view that I use is listed below (including a bit of leftover from what I tried). class DetailView(generic.DetailView): template_name = 'gts/detail.html' model = Enzymes # The active get_context_data def get_context_data(self, **kwargs): context = super(DetailView, self).get_context_data(**kwargs) enzyme = context['object'] activities = Activitydiagram.objects.filter(enzymes=enzyme) spectras = Spectraimage.objects.filter(enzymes=enzyme) enzymeactivities = Enzymeactivity.objects.filter(enzymes=enzyme) context['activities'] = activities context['spectras'] = spectras context['enzymeactivities'] = enzymeactivities return context # This was my WIP attempt """def get_context_data(self, **kwargs): context = super(DetailView, self).get_context_data(**kwargs) if self.request.user.is_staff: enzyme = context['object'] activities = Activitydiagram.objects.filter(enzymes=enzyme) spectras = Spectraimage.objects.filter(enzymes=enzyme) enzymeactivities = Enzymeactivity.objects.filter(enzymes=enzyme) context['activities'] = activities context['spectras'] = spectras context['enzymeactivities'] = enzymeactivities else: # TODO: Load only confidential=False enzymes here enzyme … -
Django & Google Auth - Error 400 (OAuth2 Error)!!1
I implemented the following views from the oauth2client documentation in Django 11.1: @oauth_required def get_profile_required(request): resp, content = request.oauth.http.request( 'https://www.googleapis.com/plus/v1/people/me') return HttpResponse(content) @oauth_enabled def get_profile_optional(request): if request.oauth.has_credentials(): # this could be passed into a view # request.oauth.http is also initialized return HttpResponse('User email: {}'.format( request.oauth.credentials.id_token['email'])) else: return HttpResponse( 'Here is an OAuth Authorize link:<a href="{}">Authorize</a>' .format(request.oauth.get_authorize_redirect())) And the pages appear to work properly, but when I attempt to go through the flow, I get the 400 error saying it's a Error: redirect_uri_mismatch. I attempted to add my domain to the credentials section for the key, but I can't locate it. Here's a screenshot of what I see: Should I be looking elsewhere? Is this a permissions issue? -
how to lazy load a nested serializer's class for a field in drf?
How to create a Generic object which has A object like below: { "_type": "A", "content_object": { "a's_field": "something..", } } and create a Generic object which has a B object like below: { "_type": "B", "content_object": { "b's_field": "something else..", "b's_field_2": "something else.." } } serializers.py class ContentObjectSerializer(serializers.Serializer): def to_representation(self, value): """ Serialize A instances using a A serializer, and B instances using a B serializer. """ if isinstance(value, A): serializer = ASerializer(value) elif isinstance(value, B): serializer = BSerializer(value) else: raise Exception('Unexpected type of tagged object') return serializer.data def to_internal_value(self, data): _type = self.parent.initial_data.get("_type", None) if not _type: return None context = self.parent.context if _type == "A": serializer = ASerializer(context=context) elif _type == "B": serializer = BSerializer(context=context) return serializer.to_internal_value(data) class GenericSerializer(ModelSerializer): content_object = ContentObjectSerializer() class Meta: model = Generic fields = ("_type", "content_object", ) def create(self, validated_data): # question = validated_data.pop("content_object") # is an ordered dictionary & not a dictionary # because of the below reason: # my guess is that parent serializer's save calls create, # passing validated_data # validations are performed and # validated_data is obtained from to_internal_value # and converted to dict models.py class Generic(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') … -
How to authorize webapp with ebay?
I am making a django app that can hold info about items i have on ebay. So, each user would have multiple ebay accounts. For example: user1 would have access to ebay1, ebay2, ebay3 account. How can I get appid, certid, devid and token for each account? The best would be to click 'add ebay account' and in new window with ebay sign in page and authorize by inserting username/password. I had a look to: https://github.com/timotheus/ebaysdk-python https://developer.ebay.com/devzone/xml/docs/reference/ebay/FetchToken.html but it is not clear to me. Can anyone provide me some step-by-step or any guidelines? Thanks in advance -
django - use result of annotate in subsequent annotate
I have the following model structure: Model A: [no question-relevant fields] Model B: linked_to = ForeignKey(A, related_name='involved') date = DateField() amount = IntegerField() what I'm trying to do is getting for each object A all the related model B, from this subset getting the latest one by date, then calculate the sum of all the model B with the same date and the same connected A object. Right now I'm using this query: A.objects.all().annotate(latest_date=Max('involved__date')) This return the correct latest date for each A object, next I'm trying: A.objects.all().annotate(latest_date=Max('involved__date')).annotate(total=Sum(Case(When(involved__date=F('latest_date'), then='involved__amount')))) But I'm getting a AttributeError: 'Case' object has no attribute 'name'. I've used multiple annotate before, without any issue, the difference is that in the past I always used previous annotated values coming from existing field, never from a Max/Min, so I'm not sure if this makes the difference. Django version is 1.8 I cannot use any raw SQL here and I know this can be easily done in 2 step, but at this point is more a personal curiosity of understanding how this works. -
What is a django alternative to {% include %} tag
In the django doc it is mentioned that {% include %} is deprecated since 1.11. Since I'm new to django, what is the alternative? Imagine you have a header of a page which is different if you are authenticated or not. I do not want to have both layouts in the header.html template... -
Is there a limit of values_list and if so what is the workaround?
I need to get all the question that have no anwsers. I guess this Django-like query is self-explaining: answers = QuizzMobileDeviceAnswer.objects.all() questions_without_answers = QuizzMobileDeviceQuestion.objects\ .filter(date_sent__isnull=False)\ .exclude(pk__in=answers.values_list('pk', flat=True)) It works flawlessly now. But if I have ~500.000 answers? values_list() will return an array of ~500.000 ids, and I guess this query wont work anymore (I've already had that problem some months ago). What is the workaround for query? -
python AES Encrypt
I am new in python/django. I want to use AES Encryption. after search I found some libraries like this: https://gist.github.com/jeetsukumaran/1291836 but I could not use them because of I have IV but this dont have IV code. I have sample code in c#. any one may help me to convert this code to python code? using System; using System.Collections.Generic; using System.Text; using System.Security.Cryptography; using System.IO; namespace AESUtility { public class AES { string AES_Key = string.Empty; string AES_IV = string.Empty; public AES(string AES_Key, string AES_IV) { this.AES_Key = AES_Key; this.AES_IV = AES_IV; } public bool Encrypt(String Input, out string encryptedString) { try { var aes = new RijndaelManaged(); aes.KeySize = 256; aes.BlockSize = 256; aes.Padding = PaddingMode.PKCS7; aes.Key = Convert.FromBase64String(this.AES_Key); aes.IV = Convert.FromBase64String(this.AES_IV); var encrypt = aes.CreateEncryptor(aes.Key, aes.IV); byte[] xBuff = null; using(var ms = new MemoryStream()) { using(var cs = new CryptoStream(ms, encrypt, CryptoStreamMode.Write)) { byte[] xXml = Encoding.UTF8.GetBytes(Input); cs.Write(xXml, 0, xXml.Length); } xBuff = ms.ToArray(); } encryptedString = Convert.ToBase64String(xBuff); return true; } catch (Exception ex) { encryptedString = string.Empty; return false; } } public bool Decrypt(String Input, out string decodedString) { try { RijndaelManaged aes = new RijndaelManaged(); aes.KeySize = 256; aes.BlockSize = 256; aes.Mode = CipherMode.CBC; aes.Padding … -
'QuerySet' object has no attribute
Please could you me why I get this error message while displaying "fav" in my template QuerySet object has no attribute game_id I tried to replace game_id by game, id_game but nothing... Thanks view.py from django.contrib import messages from django.conf import settings from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from django.shortcuts import render from start.models import Games, FavoriteGames import urllib, json # Create your views here. def view_recap(request): if request.user.is_authenticated(): username = request.user.username id_user = request.user.id fav = FavoriteGames.objects.filter(user_id=id_user).game_id return render(request, 'recap.html', locals()) else: from start.views import view_logoff from start.views import view_logon messages.add_message(request, messages.INFO, 'Vous devez être connecté pour accéder à cette page.') return redirect(view_logon) models.py from django.db import models from django.conf import settings # Create your models here. class Games(models.Model): guid = models.CharField(max_length=100, unique=True, null=False, verbose_name="GUID") title = models.CharField(max_length=100, null=False, verbose_name="Titre") logo = models.CharField(max_length=100, null=True, blank=True, verbose_name="Logo") date = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date de création") update = models.DateTimeField(auto_now=True, verbose_name="Dernière modification") def __str__(self): return self.title class FavoriteGames(models.Model): game = models.ForeignKey('Games') user = models.ForeignKey(settings.AUTH_USER_MODEL) -
Get query results to group_by in model form and get placed in select
I have a model form and I'm trying to get a dropdown to populate the select with options from the database. My model form looks like this: class CreateTripsForm(forms.Form): start_locations = Mileage.objects.values('start_location').annotate(num_locations=Count('start_location')).order_by('start_location') end_locations = Mileage.objects.values('end_location').annotate(num_locations=Count('end_location')).order_by('end_location') starting_location = forms.ModelChoiceField(queryset=start_locations, empty_label=None) ending_location = forms.ModelChoiceField(queryset=end_locations, empty_label=None) The select options are there, but they give results that are not what I'm after. The options in the select look like this: {'start_location': 'Location A', 'num_locations': 27} {'start_location': 'Location B', 'num_locations': 27} {'start_location': 'Location C', 'num_locations': 27} I just want the select to only show: Location A Location B Location C I've tried a number of different ways to accomplish this, but I feel I'm missing something. -
Related Field got invalid lookup
What can cause this error? (Pdb) foos.filter(bar__baz='Baaaz') *** TypeError: Related Field got invalid lookup: type_name (Pdb) foos.first().bar.baz 'Baaaz' (Pdb) foos [<Foo>, <Foo>] Foo object has a Foreign Key field pointing at Bar, which has baz field. -
django context menu url
This is html file to get url of the folder. <td> <a class="fa fa-file" id="openUrl" href="localexplorer:{{ work.path }}"></a> </td> This is the html file to create context menu. <menu id="html5menu" style="display:none" class="showcase"> <command label="Open File" icon="fa-edit" onclick="openfile()"> <command label="Open Folder" icon="fa-folder" onclick="openfolder()"> </menu> Jquery code to click. `$(function(){ $.contextMenu({ selector: '.right-context-menu', items: $.contextMenu.fromMenu($('#html5menu')) }); }); function openfile() { $("#openUrl")[0].click(); } function openfolder() { $("#openPath")[0].click(); }` After right click its opening same link everytime. -
Django Html context
I have a template which contains: Example 1: {% if player_mark %} {% if commun.intern > threshold %} <a class="btn btn-success btn-sm pull-right" href="{% url 'games:map:town_map' map_id=map.id home_id=homecall.id %}"><i class="fa fa-phone-square fa-fw"></i> {{ title_header }}</a> {% endif %} {% endif %} This same statement is copy and pasted about 15 times and to make it tidier i'm looking into having one and it look like this Example 2: {% if {{ player_header }} %} {% if commun.intern > threshold %} <a class="btn btn-success btn-sm pull-right" href="{% url '{{ url_header }}' map_id=map.id home_id=homecall.id %}"><i class="fa fa-phone-square fa-fw"></i> {{ title_header }}</a> {% endif %} {% endif %} then just updating it inside the context with what i need like so def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['player_header'] = ??? context['url_header'] = ??? context['title_header'] = "This is map for home town" ) return context I thought id be able to just replace the if statement in example one with contents of Example 2 but then i don't know how to structure this in the context_view. Any ideas, need anything else let me know. -
How to integrate swagger-ui with Django Rest Framework and Django-Rest-framwork-Swagger?
I am writing a Django app that exposes an API via DRF. Normally, I would generate the schema from code and expose the API docs via swagger-ui and the django rest framework swagger plugin for Django. The plugin uses 2 renderes to do so like: schema_view = get_schema_view( title='app api title', renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer] ) My use case is a bit different this time. What I am trying to do is to render an already existing swagger.yml (I dont want to generate this dynamically from code). I guessed one needs to inject the existing swagger.yml into the SwaggerUIRenderer, but I failed to do so... Is there any way to do this via the rest swagger plugin?