Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
App Engine + Django: ImportError: No module named django.core.wsgi
I'm deploying a simple Django app to Google App Engine. How can I fix the following? Traceback (most recent call last): File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 240, in Handle handler = _config_handle.add_wsgi_middleware(self._LoadHandler()) File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler handler, path, err = LoadObject(self._handler) File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 96, in LoadObject __import__(cumulative_path) File "/base/data/home/apps/s~google.com:walle120-code/20171104t152156.405293023907909181/mysite/wsgi.py", line 12, in <module> from django.core.wsgi import get_wsgi_application ImportError: No module named django.core.wsgi -
Django Admin: object is not JSON serializable error on Custom Field Sub-classing JSONField
I'm trying to de-normalize my Django Postgres database that backs a JSON API by storing certain objects in JSONFields: https://docs.djangoproject.com/en/1.11/ref/contrib/postgres/fields/#jsonfield I extended the django.contrib.postgres.fields.JSONField field to serialize data into Python objects automatically. I'm doing this in order to encapsulate my logic around the objects and to enforce the structure of the objects stored in the JSONField. I'm following the Django documentation on custom model fields here: https://docs.djangoproject.com/en/1.11/howto/custom-model-fields/ I'm able to store my objects in the custom JSONField and can retrieve them as native Python objects, however, I've broken the admin console. When I try to view one of my objects, i get this error: TypeError: <core.fields.PostalAddress object at 0x7fdcfaade4e0> is not JSON serializable I assume that the problem is that built-in json.dumps function doesn't play nicely with random objects, so I hope that there is some method I can override in my PostalAddress class to get it to play nice. Here is my code, although this is a simple case of an address, I want to apply this pattern to more complicated and useful custom JSONField use cases, so I would like to see the serialized JSON in the admin console and be able to edit the text and save … -
Geodjango custom-specific admin panel
I would like to know what is the best approche to handle indoor mapping using GeoDjango. To be more specific, I've read a lot of articles and watched a lot of tutorials, yet none of it covered a simple usage of adding an employee to a room using geodjango admin CMS. Does anyone know how I should handle it? Lets say I've an employee (Point) and a Room (Polygon). Lets say that someone choose to add/delete/move Employee in Room no. 1 from admin panel, and what I wish to achieve is to prompt to user this very room on map base map (which is an easy part), and then (somehow) I would need to load also every employee from database that is already set in this room, so he can move/delete them or add another one. Is this even possible to do? I would really appreciate any kind of help. Links to tutorials, articles, and so on (if there are any that I wasn't able to find, because I've spent a lot of time to find it). Also if this is impossible, maybe someone can tell me what would be the way to go, considering that I need to create … -
Django Admin: Making Sure a model is accessed by one user at a time
I have a Django Model instance and I want to make sure it is accessed by one user at a time on the Django Admin site. Example: User_1 logs in to Django Admin and accesses this model instance. Now User_1 can see all the fields and edit them. Meanwhile, User_2 opens the same model in Django admin. User_2 can't edit this model and all actions are disabled. As soon as User_1 closes this form (navigating away from form) User_2 can edit it. I have thought of using Django signal but don't know how to go about it. -
what does run the command \dt mean?
I'm teaching myself django. At this site https://docs.djangoproject.com/en/1.11/intro/tutorial02/ It says If you’re interested, run the command-line client for your database and type \dt (PostgreSQL), SHOW TABLES; (MySQL), .schema (SQLite), or SELECT TABLE_NAME FROM USER_TABLES; (Oracle) to display the tables Django created. I really don't know what that means. Do they want me to input some commands in the terminal? If so what commands? -
Django project printing to console instead of browser
What I'm trying to do: Translate input -> pig latin onclick and display output. See code below: class translator: def pigLatin(sentence): translation = " " for word in sentence.split(): if word[0] in "aeiou": translation += word + "yay " if word[0] and word[1] not in "aeiou": translation += word[2:] + word[0:2] + "ay" print("hai") else: translation += word[1:] + word[0] + "ay " return translation sentence = input("Enter word/sentence you want translated to pig latin below: ") print(pigLatin(sentence)) What's happening: As soon as I run my local server, the above input prompt ^ appears in console, as seen below: translator running in console Problem being, I want this to appear in my browser onclick. Instead, when I click my "translate" button, it just repeats my translate div in the output section. (see below image for clarity.) translator in browser Other relevant code/file structure: Views.py from django.shortcuts import render from django.http import HttpResponse from pigLatinApp import pigLatinTranslator def index(request): return render(request, 'pigLatinApp/home.html') def output(request): if request.is_ajax(): py_obj = pigLatinTranslator.translator return render(request, 'pigLatinApp/home.html', {'output': py_obj}) Templates header.html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1"> <title>Pig Latin Translator</title> {% load staticfiles %} <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}" type="text/css"> </head> <body … -
Creating a foreign key for user from one app to another in Django
I wanted to create a user foreign key in my tasks models.py to another table called UserProfile. I want a task to be associated to a user so when I go to query it and display it in a profile page, I don't see anyone else's. However, when I attempted this, I got this error: This is my tasks.model.py This is my useraccounts.models.py -
Django Field and Widget and __deepcopy__
I want to create a custom field with custom in Django. Because I like to understand how things are working I checked the Django code, and I see that in Field class widget = widget or self.widget if isinstance(widget, type): widget = widget() else: widget = copy.deepcopy(widget) The Field class is overwriting the default deepcopy def __deepcopy__(self, memo): result = copy.copy(self) memo[id(self)] = result result.widget = copy.deepcopy(self.widget, memo) result.validators = self.validators[:] return result Also the Widget class do the same thing. def __deepcopy__(self, memo): obj = copy.copy(self) obj.attrs = self.attrs.copy() memo[id(self)] = obj return obj I know what copy and deepcopy does (did some examples), I want to understand why Django needs a deepcopy of the widget and why is overwriting the default __deepcopy__ ? -
Datatable ajax add row on condition
So I'm having some trouble setting up datatable using Ajax. Some context: I have a Ajax that request certain files information. The response contains two sets The files information The users information (to figure out the user of the files). I've completed the entire logic without Datatable but now i want to implement it using datatable. I have 2 condition Is the end date between today and 4 days from now? is the end date after 4 days form now? These condition are used to indicate to the user witch files (project) needs the most attention. CODE TIME (I'm using the Django framework btw) :D The AJAX CALL function ajax_dates() { $.ajax({ url: "{% url 'get_files_dates' %}", type: "GET" }).done(function (object) { date_calculation(object.dates, object.users); }); } THE TWO CONDITION // CONDITION ONE (ATTEMPT using Datatable) // Projecten met een waarschuwing if (enddate.isBetween(today, today.clone().add(4, 'd'))) { // TABLE ROW VOOR ELK TYPE running_waring = ""; running_waring += '<tr>'; running_waring += '<td>'+ checker.first_name + " " + checker.last_name+'</td>'; running_waring += '<td>'+ checker.first_name + " " + checker.last_name+'</td>'; running_waring += '<td id="testing">'+result.name+'</td>'; running_waring += '<td>'+result.word_count+'</td>'; running_waring += '<td>'+enddate.format("D MMM YYYY").replace(".","")+'</td>'; running_waring += '<td>'+enddate.format("HH:mm:ss")+'</td>'; running_waring += '<td>Verloopt binnenkort </td>'; running_waring += '<td> Verloopt' + … -
Add css class to all admin form field
I need to assign a boostrap class to all my user's field in Django admin form, I wrote this code but it does not work. formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'class': 'form-control'})}, models.CharField: {'widget': EmailInput(attrs={'class': 'form-control'})}, models.DateField: {'widget': DateTimeInput(attrs={'type': 'date', 'class': 'form-control'})}, models.EmailField: {'widget': EmailInput(attrs={'class': 'form-control'})}, models.BooleanField: {'widget': CheckboxInput(attrs={'class': 'form-control'})}, } Can you help me? -
invalid PasswordChangeForm
Heyho, I created a model Profile with a OnetoOneField to User. In account_settings view I want to either give the possibility to change the profile information or reset the password. Changing Profile-Information works fine, but when I try to change the password, my PasswordChangeForm is always invalid. Can somebody tell me where my mistake is? Here's the view: def account_settings(request, id): user = Profile.objects.get(id=id) if request.method == 'POST' and 'passwordchange' in request.POST: user_form = PasswordChangeForm(request.user, prefix='password') if user_form.is_valid(): user_form.save() update_session_auth_hash(request, user) messages.success(request, 'Your password was successfully updated!') else: messages.error(request, 'Please correct the error below.') return redirect('profile', user.id) elif request.method == 'POST' and 'profilechange' in request.POST: profile_form = ProfileForm(request.POST, instance=request.user.profile,prefix='profil') if profile_form.is_valid(): profile_form.save() return redirect('account_settings',user.id) #else: #messages.error(request, _('Please correct the error below.')) else: user_form = PasswordChangeForm(user=request.user, prefix='password') profile_form = ProfileForm(instance=request.user.profile,prefix='profil') return render(request, 'app/accountform.html', {'profileuser': user,'user_form': user_form,'profile_form': profile_form}) the template: <div class="col-md-9"> <div class="profile-content"> <form method="post" > {% csrf_token %} {{ profile_form.as_p }} <button type="submit" name="profilechange">Änderungen speichern</button> </form> <form method="post" > {% csrf_token %} {{ user_form.as_p }} <button type="submit" name="passwordchange">Passwort ändern</button> </form> <a href="{% url 'profile' user.profile.id %}" type="submit" class="btn btn-default">Abbrechen</a> </div> </div> -
form.is_valid() always returns false in views.py
form.is_valid() always fails. I tried different ways to handle it but fails every time and it returns false. Please help in figuring out whats wrong with the code. models.py looks like this - class Album(models.Model): album_name = models.CharField(max_length=50, primary_key=True) place = models.CharField(max_length=50) date_pub = models.DateTimeField('date published') def __str__(self): return self.album_name class Images(models.Model): album_name = models.ForeignKey(Album, db_column='album_name') image_name = models.CharField(max_length=40) image = models.FileField(null=True, blank=True) upload_dt = models.DateTimeField(auto_now=True, auto_now_add=False) like_cntr = models.IntegerField(default=0) description = models.CharField(max_length=200, null=True) def __str__(self): return self.image_name forms.py is - class ImagesForm(forms.ModelForm): description = forms.CharField(required=False) class Meta: model = Images fields = ('album_name', 'description',) views.py is - class RandomView(TemplateView): template_name = 'photos/random.html' def get(self, request, album_name): images = Images.objects.filter(album_name=album_name) context = {'album_name':album_name, 'images' : images} return render(request, 'photos/random.html', context) def post(self, request, album_name): form = ImagesForm(request.POST) if form.is_valid(): form.save(commit=False) text = form.cleaned_data['description'] Images.album_name = album_name form.save() else: return HttpResponse("Failed to save") Templates is - <h3>Album : {{album_name }}</h3> {% for image in images %} <img src="{{image.image.url}}" height="400" width="500"> <h4> {{image.image_name }}</h4> <form method="POST" action=""> {% csrf_token %} <span class = "badge">Description</span> {% if image.description %} <h4> {{image.description }} </h4> {% else %} <input type="text" value=" "/> <button type="Submit">Submit</button> {% endif %} </form> {% endfor %} -
how to override GET method in django to make a seen status
I wanna make this thing on the model as I'm using REST API too. I have a model named as seen active = models.BooleanField( verbose_name=_("Is active"), default=True, help_text=_("Inactive devices will not be sent notifications") ) user = models.ForeignKey( SETTINGS["USER_MODEL"], blank=True, null=True, on_delete=models.CASCADE ) and I wanna to override my customise class-based view so that everytime an authenticated user visits a detail view I create an instance in the seen table -
How to use CSRF token in cached views?
I'm using Redis to cache views. But I can't use forms in the cached views because of the CSRF token. How can I use forms in a cached view? -
Django oauth toolkit Permission for access_token generated by client_credential
I am using Django oauth toolkit with django-restframework for implementing a sets of Apis for a client application. My problem is when i genereting a token with grant client_credentials i get 403 in access on my view (in access token table there is not set a user). How can solve this issue ? Best Luca -
Signup page stuck on loading (Waiting for Localhost...) after extending AbstractUser
I created a custom user model called Agent by extending AbstractUser. Now for some reason, my signup page is stuck and I can't figure out why (it was working fine before I created the custom user). When I click the Sign Up button, the page is stuck on Waiting for localhost... There are 2 additional models on top of Agent that are created during registration - AgentBasicInfo and AgentPremiumInfo. AgentBasicInfo is displayed on the sign up page, while AgentPremiumInfo is created in the background, and not actually displayed during registration. When I check my admin page, I see that an Agent model has been created, but no AgentBasicInfo and AgentPremiumInfo instances have been created. This leads me to believe something is getting stuck at or after agent_basic_info = basic_info_form.save(commit=False), but I can't figure out what it is. Here is my code: views.py def signup(request): if request.user.is_authenticated: return HttpResponseRedirect('../dashboard/') if request.method == 'POST': signup_form = SignupForm(request.POST) basic_info_form = AgentBasicInfoForm(request.POST) if signup_form.is_valid() and basic_info_form.is_valid(): agent = signup_form.save(commit=False) agent.is_active = False agent.save() # Creates a basic info form with user input agent_basic_info = basic_info_form.save(commit=False) agent_basic_info.agent = agent agent_basic_info = agent_basic_info.save() # Creates a profile model with the agent's premium information, empty except for … -
CourseModuleUpdateView didn't return an HttpResponse object. It returned None instead
I have the following class for displaying related course module using formsets class CourseModuleUpdateView(TemplateResponseMixin, View): template_name = 'courses/manage/module/formset.html' course = None def get_formset(self, data=None): return ModuleFormSet(instance=self.course, data=data) def dispatch(self, request, *args, **kwargs): self.course = get_object_or_404(Course, id=kwargs['pk'], owner=request.user) super(CourseModuleUpdateView, self).dispatch(request, *args, **kwargs) def get(self, request, *args, **kwargs): formset = self.get_formset() return self.render_to_response({'course': self.course, 'formset': formset}) Url pattern responsible for this CBV url(r'^(?P<pk>\d+)/module/$', views.CourseModuleUpdateView.as_view(), name='course_mudule_update') Issuing a get request I get the following error Traceback: File "/home/mtali/.virtualenvs/educa/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/home/mtali/.virtualenvs/educa/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 198. "returned None instead." % (callback.__module__, view_name) Exception Type: ValueError at /courses/4/module/ Exception Value: The view courses.views.CourseModuleUpdateView didn't return an HttpResponse object. It returned None instead. What is wrong with my code! I am using django 1.11 -
Legacy Django 1.4.22 app to Django 1.11
I am migrating a legacy Django 1.4.22 app to Django 1.11 I have gone through https://groups.google.com/forum/#!topic/django-users/_cES27L7Y18 https://django.readthedocs.io/en/1.4.X/topics/generic-views-migration.html https://www.seedinvest.com/labs/backend/upgrading-from-django-1-4-to-django-1-7 https://bertelsen.ca/updating-django-1-4-to-1-10-learnings/ https://timony.com/mickzblog/2017/09/27/migrate-django-1-4-to-1-11/ Upgrading a django 1.4 project to 1.8 version https://docs.djangoproject.com/en/1.8/releases/1.5/ https://docs.djangoproject.com/en/1.8/releases/1.6/ https://docs.djangoproject.com/en/1.8/releases/1.7/ https://docs.djangoproject.com/en/1.8/releases/1.8/ https://openedx.atlassian.net/wiki/spaces/PLAT/pages/160667796/edx-platform+Django+1.11+Upgrade+Plan https://docs.djangoproject.com/en/1.11/howto/upgrade-version/ Looking for more "hands-on" tips to help me complete this -
django oscar migrations not migrating, other app migrates
I've been quite stuck and I've read the docs over and over again. My models aren't migrating. My prompt would be No changes detected in app "catalogue" but I did make changes. I can't seem to figure out what I'm doing wrong. Sometimes it works and I don't know why. I make note of it and repeat it, it doesn't work. Any suggestion or idea is appreciated. Thanks!!! subapp1 is the shop app using oscar, subapp2 is another app I run python manage.py makemigrations catalogue then python managepy migrate catalogue I've also tried migrating in the subapp1. Result is the same. app/settings.py INSTALLED_APP = [...] + + get_core_apps(['subapp1.catalogue']) I've also forked the migrations folder as indicated in the docs. I also tried without it. (And yes I have my __init.py__ file. app/subapp1/catalogue/models.py from django.db import models from django.utils.translation import ugettext_lazy as _ from subapp2 import models as subapp2_models from oscar.apps.catalogue.abstract_models import AbstractProductImage from oscar.core.loading import get_model product = get_model('catalogue','Product') links = subapp2_models.links class ProductImage(AbstractProductImage): links= models.ForeignKey(links) product = models.ForeignKey('catalogue.Product', related_name='photo_links', verbose_name=_("Product")) class Meta: app_label = 'catalogue' verbose_name = _('link image') def __str__(self): return u"Image of '%s'" % self.product from oscar.apps.catalogue.models import * -
Graphene-django returns null node instead of just node field
I am facing a strange problem with graphene and Django. The documentation seems to lack a solution and I couldn't figure out what I'm doing wrong. I have the following models: Class Sentence(models.model): ref = models.CharField(max_length=30, primary_key=True) body = models.TextField(default=None) Class Summary(models.Model): sentence = models.ForeignKey(Sentence, on_delete=models.CASCADE) text = models.TextField(default=None) (Each sentence can have multiple summaries) And the following schema: Class SentenceType(DjangoObjectType): class Meta: model = models.Sentence filter_fields = {"ref": ["exact"]} interfaces = (graphene.Node, ) Class SummaryType(DjangoObjectType): class Meta: model = models.Summary filter_field = {"text": ["icontains"]} interfaces = (graphene.Node, ) Class Query(graphene.ObjectType): all_sentences = DjangoFilterConnectionField(SentenceType) sentence = graphene.Field(SentenceType, ref=graphene.string(), body=graphene.string()) all_summary = all_provvedimenti = DjangoFilterConnectionField(SummaryType) summary = graphene.field(SummaryType, id=graphene.Int(), text=graphene.string()) def resolve_all_summaries(self, context, **kwargs): return models.Summary.objects.all() It can occur that there is one or more summaries in my database with no corresponding sentence. Now, when I query { allSummaries{ edges{ node{ text sentence{ ref } } } } } If the the sentence exists for the summary, no problem at all. But if there is no corresponding sentence I get: "errors": [ { "message": "Sentence matching query does not exist.", "locations": [ { "line": 6, "column": 9 } ] } ], ..., ..., "data":[ ..., { "node": null }, { "node":{ … -
Serializer List of objects grouping them by foreign key attribute
Similar to the issue found here (and maybe here) I had the problem of having a model like so: class Item(models.Model): name = models.CharField(max_length=128) category = models.ForeignKey(Category) class Category(models.Model): name = models.CharField(max_lenght=64) and wanting to serialize a list grouped by category like so: [{'name': 'category 1', 'items: [ {'name': 'item1}, {'name':'item2'} ]}, {'name': 'category 2', 'items: [ {'name': 'item3}, {'name':'item4'} ]}] -
How to test a Django CreateView
I want to practice testing on Django, and i have a CreateView i want to test. The view allows me to create a new post and i want to check if it can find posts without a publication date, but first i'm testing posts with published date just to get used to syntax. This is what i have: import datetime from django.test import TestCase from django.utils import timezone from django.urls import reverse from .models import Post, Comment # Create your tests here. class PostListViewTest(TestCase): def test_published_post(self): post = self.client.post('/post/compose/', {'author':"manualvarado22", 'title': "Super Important Test", 'content':"This is really important.", 'published_date':timezone.now()}) response = self.client.get(reverse('blog:post_detail')) self.assertContains(response, "really important") But i get this: django.urls.exceptions.NoReverseMatch: Reverse for 'post_detail' with no arguments not found. 1 pattern(s) tried: ['post/(?P\d+)/$'] How do i get the pk for that newly created post? Thank you! -
How can i combine 2 programs written in different programming languages together
I have a django web app and my friends have made a messaging app in erlang and I want to combine both of them so that the users and their friends can communicate. We are trying build something like facebook, their main web languages is php but they use erlang for messanger -
Reduce amount of queries for generic foreign key
Suppose I have these models: class RegionPage(models.Model): area = models.ForeignKey('Area') title = models.CharField(max_length=255) class SomePage(models.Model): someotherfield = models.ForeignKey('SomeClass') title = models.CharField(max_length=255) class Link(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntergerField() content_object = GenericForeignKey('content_type', 'object_id') title = models.CharField(max_length=255) Obviously, I can use neither select_related nor prefetch_related to get access to someotherfield and area fields. But is there any way to reduce amount of queries when you work with generic foreign keys? -
AttributeError: 'module' object has no attribute 'TabularInLine'
What could be the problem in this code I am trying to add Cart in an e-commerce page and it return with an Attribute Error from django.contrib import admin from .models import Cart, CartItem class CartItemInLine(admin.TabularInline): model = CartItem class CartAdmin(admin.ModelAdmin): inlines = [ CartItemInLine ] class Meta: model = Cart admin.site.register(Cart, CartAdmin)