Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploying Django on Apache server: mod_wsg causing error
mod_wsgi: Compiled for Python/2.7.11. mod_wsgi: Runtime using Python/2.7.12. This causes a SIGTERM and results in a 500 error. How do I fix this?? How can I compile mod_wsgi for Python/2.7.12? OS is Ubuntu by the way. -
How to display upload multi files's count in django admin?
I can upload multi files ,but how to display multi files count at list_display... models.py class PaperManager(models.Model): ... class PaperFile(models.Model): image = models.FileField(upload_to='upload/') project = models.ForeignKey(PaperManager) admin.py class PaperFileAdmin(admin.ModelAdmin): pass class ProjectFileInline(admin.StackedInline): model = PaperFile max_num=10 extra=0 admin.site.register(PaperFile, PaperFileAdmin) class PaperAdmin(admin.ModelAdmin): inlines = [ProjectFileInline, ] list_display = ('id', ...) ... admin.site.register(PaperManager,PaperAdmin) Thanks -
two of the same instance and configuration but one keep show nginx welcome page
I have a running instances which shows the site properly on aws. what's included to run the site are django, nginx, uwsgi with elastic ip I have created an image of the instances. Launch the instance which now I have a second instance which is the same as the first one. The second instance just have normal floating ip. When I input the ip into the browser, I was expecting to see my site too else just a long loading until it timeout since I didn't do any configurations in site-available yet. Anyways, I was then able to see only the nginx welcome page. I went to the site-available, put the ip into server_name, also I setup a dns for a subdomain name. After the changes, I restarted uwsgi. I tried using ip and subdomain on browser, but still showing the nginx welcome page. There isn't even an error. Does someone have any idea why or advice what I do try? They are both the same settings, shouldn't it work properly? P.S. I then tried moving the elastic ip from first instance to the second instance...I used the domain of first instance in browser...then my site pops up not the … -
highlight bokeh plot point on div mouseover using django
I want to have points on a bokeh plot glow or light up when a mouseover event occurs on the corresponding Div element. Is this possible? Is there a better plotting library for this? Any help much appreciated. The following Github repository contains my code: https://github.com/matt002/dynamic_plot_django.git -
How to get a request object inside urls.py
I am trying to use custom template on page_not_found default handle Inside urls.py from django.views.defaults import page_not_found handler404 = page_not_found(request, None, "pages/custom/404.html") page_not found method requires request, exception and template. So how can i get the request object. I know the alternative for using it inside views.py -
django forms and javascript
I want to include a simple Javascript function in my Django ModelForm to automatically calculate the Gross by multiplying Price and Quantity but I am not able to get it done. Below is my django code and HTML Code with JS Function: class TransactionForm(forms.ModelForm): class Meta: model = Transaction fields = ['Date', 'Fruits', 'Deal', 'Price', 'Quantity', 'Gross', 'Area'] widgets = { 'Date': DateInput(), 'Price': forms.TextInput(attrs={"id": "price", "onchange": "calculate_gross();"}), 'Quantity': forms.TextInput(attrs={"id": "qty", "onchange": "calculate_gross();", }), 'Gross': forms.TextInput(attrs={"id": "gross", "disabled":"true"}), } <script> function success() { alert('Transaction added successfully'); } </script> <script> function calculate_gross() { var price = parseFloat(document.getElementById('price').value); var qty = parseFloat(document.getElementById('qty').value); var gross = price*qty; document.getElementById('gross').value = gross; } </script> <h1>Enter Transaction Below</h1> <form method="post"> {% csrf_token %} {{form.as_p}} <input type="submit" name="Submit" onclick="success();"> </form> Any support would be much appreciated. Thank You. -
Django Rest Framework: Patching a OneToOneField
I need help with a PATCH request using Django rest framework. I have a User model that inherits from AbstractBaseUser which has 2 fields: name and email. The email field is unique. Then I have a DojoMaster model that has a OneToOne relationship with the User model: models.py class DojoMaster(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) phone = models.BigIntegerField() username = models.CharField(max_length=100, unique=True) country = models.ForeignKey(Country, on_delete=models.CASCADE) I am able to POST a "dojomaster" to the application. Let's say the "dojomaster" POST looks like this: POST payload { "user": { "name": "XYZ", "email": "xyz@mail.com", "password": "2He$8Mv*" }, "phone": 2685211, "country": 575, "username": "iAmXyZ" } Now the "dojomaster" wants to change some of these details, so a PATCH request is sent: PATCH payload { "user": { "name": "XYZ", "email": "xyz24@mail.com", #change email "password": "p@55w0rd" #change password }, "phone": 3972925, #change phone number "country": 575, "username": "iAmXyZ" } To achieve this, I created the following in my serializers.py: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('name', 'email', 'password') class DojoMasterUpdateSerializer(serializers.ModelSerializer): user = UserSerializer(required=True) def update(self, instance, validated_data): user_data = validated_data.pop('user') user = User.objects.update(**user_data) instance.user = validated_data.get('user', user) instance.username = validated_data.get('username', instance.username) instance.phone = validated_data.get('phone', instance.phone) instance.country = Country.objects.get( country=validated_data.get('country', instance.country) ) … -
Changing Tableau display name of Django model fields
I have been using Django ORM with Tableau reports without many issues, by providing the label for the fields explicitly. E.g. my_field = models.CharField("A Better Looking Name", max_length=500) So the above shows up in Tableau reports as "A Better Looking Name". However, when using the contenttype framework, I am unable to provide the labels for field columns: object_id = models.TextField('Give whatever name here it does not work') content_type = models.ForeignKey(ContentType, ...) my_field = GenericForeignKey("content_type", "object_id") I have tried providing verbose_name for object_id, renaming my_field, etc. None of them translate to a changed label in the PostgreSQL database (and hence in Tableau). Note that I am NOT attempting to label these for Admin etc, so short_description is not of use here. Any input on how to use "A Better Looking Name" for the generic ID in Tableau would be appreciated. -
Ajax and Django to get a multi-select smart panel to work
Please any idea how i can achieve something like this with Ajax and Django. Lets say a medical app. I'll like to multi-select medicine while it shows in a different panel and add the amount(s) sum and show me like the right text-boxes.. -
Issue With Same Inbox Subject as Multiple Objects
I'm using this Django Messages package. Messages in the inbox with the same subject keeps showing up more than once depending on the number of times a sender and the recipient receives messages. I want a situation whereby messages with the same subject will only show up once in the inbox and not twice or thrice. Kindly check the attached image for what I mean. I've looked into the code and I did this message_list = Message.objects.inbox_for(request.user).values('subject').distinct() But still not working. -
Django assign score to the field based on the choice and calculate the sum of field scores
I am new to django and have been breaking my head for last couple of days over this problem. So I have something similar in models.py: class RType(models.Model): rtype_name = models.CharField(max_length=10, verbose_name="Severity", default = "") rtype_score = models.IntegerField(max_length=10, verbose_name="Severity Score", default = "") def __str__(self): return self.rtype_name class Environment(models.Model): environment_name = models.CharField(max_length=100, verbose_name="Environment") environment_sensitivity = models.ForeignKey(RType, on_delete=models.CASCADE, blank=True, null=True, verbose_name="Environment sensitivity", default = "") def __str__(self): return self.environment_name class UserGroup(models.Model): user_group_name = models.CharField(max_length=100, verbose_name="User Group") user_group_sensitivity = models.ForeignKey(RType, on_delete=models.CASCADE, blank=True, null=True, verbose_name="User Group sensitivity", default = "") def __str__(self): return self.user_group_name class Subject(models.Model): name = models.CharField(max_length=500, verbose_name="Subject", blank=True) question1 = models.ManyToManyField(UserGroup, verbose_name="User group", default="", blank=True) question2 = models.ManyToManyField(Environment, verbose_name="Environment", default="", blank=True) r = ?? Here are some things I want to achieve: Sum rtype_scores for each question (question1, question2) even if there are multiple choices Count number of choices made in question1 Make other calculations like / * + - on inputs from question, question and count results Store the outcome of calculations in r Is this even possible or am I doing everything incorrectly? -
Set testing options while django doctesting
Following these posts, I have managed to run my doctest within django with: # myapp/tests.py import doctest def load_tests(loader, tests, ignore): tests.addTests(doctest.DocTestSuite()) return tests Then running: python manage.py tests However, since I am used to test my (non-django) scripts with the simple command: py.test --doctest-modules -x I am now quite confused about: testing procedure not stopping after first failure (my good'ol -x) (so I get flooded with results and I need to scroll back all the way up to the first problem each time) option # doctest: +ELLIPSIS not being set by default. How do I set this kind of options from this django load_tests() hook? -
Want to have django-two-factor-auth skip token if user logged in during the last 30 days
First, if anyone has done this, please advise :) Right now, I am thinking of subclassing WizardView's method render_next_step() (from the formtools package). the 1st line of the new method would be: if self.steps.next == 'token': (pseudo code) if user_agent == current user_agent and last_activity < 30 days ago (from table user_sessions_session): return # skip the token step Comments, suggestions welcome -
Django user.is_staff not working
i am in trouble with my django projet. I would like to do that only staff user can see a link (href) in a template. The template in which is the code bellow is the template base.html that I take in my other templates. here is the header of base.html <header class="header"> <img src="{% static 'img/headerWAI.jpg' %}" alt="HeaderWai jpg" class="headerimg" /> <h1 class="headerText">Waste Annotation Image</h1> <p class="usermenu"> {% block loginuser %} {% if user.is_authenticated %} Hello {{ user.username }}! <p><a class="loginlink" href="{% url 'logout' %}">logout</a> {% if user.is_staff %} <a href="{% url 'newimage' %}">manage image</a></p> {% endif %} {% else %} <p>You are not logged in : <a href="{% url 'login' %}">login</a></p> {% endif %} {% endblock %} </p> user.if_authenticatted work correctly but 3 lines bellow, user.is_staff not work. Out of 5 test users, only 2 have the boolean at True as staff. But when I am connect with a non-staff user, he has the link. I don't understand why? Maybe i have forgot an import or something in the settings.py Any suggestion ? PS: i am a beginner in django -
How to save user id to inline models in Django admin?
I have these Django models (minimal data for brewity): # models.py class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(Author) class AuditLog(models.Model): user = models.ForeignKey(User) # standard User model info = JSONField(default=dict) I know how to create inline admin for Books in AuthorAdmin but the problem is, I need to save AuditLog with information about who added each of the inline objects. I know I can make something like this to get the user upon saving Author: # admin.py @admin.register(Author) class AuthorAdmin(admin.ModelAdmin): inlines = [BookInline] def save_model(self, request, obj, form, change): AuditLog.objects.create(user=request.user, info={'blah': 'blahblah'}) super().save_model(request, obj, form, change) But what should I do to save the info about the user that added a new Book (eg. after some time) using the inline formset? BaseInlineFormSet methods don't support this. -
How to post data of logged in user with a form in Django?
I am creating a form for users to book times on my web app. Currently I have the following files. see forms.py: class BookingForm(forms.ModelForm): usname = User.username daterequired = forms.CharField(max_length=60, required=True) students = forms.CharField(max_length=60, required=True) length = forms.CharField(max_length=60, required=True) class Meta: model = Booking fields = "__all__" see models.py: class Booking(models.Model): usname = User.username daterequired = models.DateField(_("Date"), default=datetime.date.today) students = models.CharField(max_length=200) length = models.CharField(max_length=40, blank=True) see views.py: @login_required def choose(request): if request.method == 'POST': form = BookingForm(request.POST) if form.is_valid(): form = form.save(commit=False) form.save() return redirect('index') else: form = BookingForm() return render(request, 'choose.html', {'form': form}) What I am trying to achieve is that when a user clicks submit on the form that their user data automatically gets logged in the bookings table on the database. At the minute the only data getting logged in the table is the date field, students and length. I need to know which user is posting this data. Can anyone help? -
Django field extending UserCreationForm not showing up in view
What I'm trying to accomplish is to extend UserCreationForm to add an e-mail field for each user when they sign- up. Currently I have a form from UserCreationForm with username and password but no e-mail. I extend it with the forms.py file and implement it in my views.py. But when I run tests and look at the signup page the e-mail field is not found. views.py: from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import login as auth_login from .forms import SignUpForm # Create your views here. def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() auth_login(request, user) return redirect('index') else: form = SignUpForm() return render(request, 'signup.html', {'form': form}) forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class SignUpForm(UserCreationForm): email = forms.CharField(max_length = 254, required = True, widget = forms.EmailInput()) class Meta: model = User fields = ('username', 'email', 'password1', 'password2') form.html: {% load widget_tweaks %} {% for field in form %} <div class="form-group"> {{ field.label_tag }} {% if form.is_bound %} {% if field.errors %} {% render_field field class="form-control is-invalid" %} {% for error in field.errors %} <div class="invalid-feedback"> {{ error }} </div> {% endfor %} {% … -
Saving image/file uploads using react-redux to Django Rest Api Fails
I have been trying to submit and save form contents to django backend API. My project's frontend is done in reactjs. To connect the data flow i'm using React-Redux, to django rest framework. I'm using fetch function in redux action.(We can't use ajax or other 'react-less things'.). The form submission is working fine when upload field is removed. but the image upload fails. after submission, on console, i can see the image also reached till action. but saving it to API is not working. It is causing error: Django REST API, it shows the error "the submitted data was not a file. Check the encoding type on the form." Please help me. Please see the demo here -
routeParams keep returning empty dictionary
i'm using django/angular and trying to retrieve the 1234 parameter in url in http://localhost:8000/dashboard/1234. So far i've created a config file with the routing and a controller where i try to retrieve the id. however i keep getting {} in the console.log and then this error Error: $compile:tpload Error Loading Template var app = angular.module("App", ["ngRoute", "ngCookies"]); app.config(function ($routeProvider, $locationProvider) { $routeProvider.when('/dashboard/:id', { templateUrl: '/dashboard/', controller: 'DashboardController' }).otherwise({ redirectTo: '/' }); $locationProvider.html5Mode({ enabled: true, requireBase: false }); }); and in my controller i'm trying to output the routeParams (function () { 'use strict'; angular .module('App') .controller('DashboardController', DashboardController); DashboardController.$inject = ['$location', '$scope', '$routeParams', 'Dashboard']; function DashboardController($location, $scope, $routeParams, Dashboard) { var vm = this; console.log($routeParams) } }); -
Showing current user instance in edit profile form
So I have this view which displays my UserProfileForm. As far as I can tell the logic of what's going on makes sense. It should (1) automatically pull the profile info from the currently logged in user and (2) save it when submitted. The only problem is that it does neither of those two things. I have looked around SO for how to do this as well as some other tutorials but it still won't do the trick. The view: def editProfileView(request): if request.method == 'POST': form = UserProfileForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect('users:explore') else: form = UserProfileForm(instance=request.user) args = {'form':form} return render(request, 'users/userprofile_edit_form.html', args) Not sure how relevant seeing the form itself is but this is what it looks like: class UserProfileForm(forms.ModelForm): first_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control mb-3'})) profile_pic = forms.ImageField(widget=forms.FileInput(attrs={'class':'form-control mb-3'}), required=False) location = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control mb-3'})) title = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control mb-3'})) user_type = forms.ChoiceField(choices=USER_TYPE_CHOICES) website = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control mb-3'})) about = forms.CharField(widget=forms.Textarea(attrs={'class':'form-control mb-3'})) twitter = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control mb-3'})) dribbble = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control mb-3'})) github = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control mb-3'})) class Meta: model = UserProfile fields = ( 'first_name', 'profile_pic', 'location', 'title', 'user_type', 'website', 'about', 'twitter', 'dribbble', 'github' ) -
Django filter queryset optimization
I'm using django-filter and i have 40k+ record that comes from filter. def index(request): cleaned_objects = Mymodel.objects.filter(is_deleted=False) my_objects = ReportFilter(request.GET,queryset=cleaned_objects) and i'm giving some filter for example created_at__gte = 01.01.2011 and this query retrieve 40k records i also using django pagination but i'm getting timeout error. So how can i fix that timeout error and which optimization should i use. -
Connection Pooling across several processes in Pymongo
I'm a rather new to Pymongo and Mongodb itself and right now i'm working on a Django based project that uses a process to perform some cruds on a Mongodb instance we are using PyMongo and since this is web application many instances might be running at the same time so my questions is about the connection pool setup. what's the best practice to use the Pymongo keeping in mind performance for this specific case: connection pool? At the beginning we had a new instace of Pymongo created: MongoClient(host, port, maxPoolSize=200) every time the endPoint was called. i understand that every instance is using it's own connection Pool but when you have many instances running..do you have multiple connections pool per Mongodb instance? So we came with a modification and now instead creating new instances we just use static method which actually serves the connection method and this is shared across all of the PyMongo instances being invoked is this a good solution or is it better the first one (instance per call) or is there another option that i should follow?? I would appreciate the comments or suggestions from other guys more experienced in this matter. Thanks in advanced … -
Error - Rebuild search index with django-oscar
I'm following the django documentation to integrate solr with django-Oscar.I'm getting the following error when trying to rebuild the index.How can I fix this issue? $python3 manage.py rebuild_index --noinput Removing all documents from your index because you said so. Failed to clear Solr index: Solr responded with an error (HTTP 500): [Reason: Error 500 {msg=SolrCore 'collection1' is not available due to init failure: Schema Parsing Failed: unknown field 'id'. Schema file is /home/asanka/Music/devBranch/dailyDeal_v3/main_app/solr-4.7.2/example/solr/collection1/schema.xml,trace=org.apache.solr.common.SolrException: SolrCore 'collection1' is not available due to init failure: Schema Parsing Failed: unknown field 'id'. Schema file is /home/asanka/Music/devBranch/dailyDeal_v3/main_app/solr-4.7.2/example/solr/collection1/schema.xml at org.apache.solr.core.CoreContainer.getCore(CoreContainer.java:827) at org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatchFilter.java:305) at org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatchFilter.java:205) at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1419) at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:455) at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:137) at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:557) at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:231) at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1075) at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:384) at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:193) at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1009) at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135) at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:255) at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:154) at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116) at org.eclipse.jetty.server.Server.handle(Server.java:368) at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:489) at org.eclipse.jetty.server.BlockingHttpConnection.handleRequest(BlockingHttpConnection.java:53) at org.eclipse.jetty.server.AbstractHttpConnection.content(AbstractHttpConnection.java:953) at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.content(AbstractHttpConnection.java:1014) at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:861) at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:240) at org.eclipse.jetty.server.BlockingHttpConnection.handle(BlockingHttpConnection.java:72) at org.eclipse.jetty.server.bio.SocketConnector$ConnectorEndPoint.run(SocketConnector.java:264) at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:608) at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:543) at java.lang.Thread.run(Thread.java:748) Caused by: org.apache.solr.common.SolrException: Schema Parsing Failed: unknown field 'id'. Schema file is /home/asanka/Music/devBranch/dailyDeal_v3/main_app/solr-4.7.2/example/solr/collection1/schema.xml at org.apache.solr.schema.IndexSchema.readSchema(IndexSchema.java:618) at org.apache.solr.schema.IndexSchema.(IndexSchema.java:166) at org.apache.solr.schema.IndexSchemaFactory.create(IndexSchemaFactory.java:55) at org.apache.solr.schema.IndexSchemaFactory.buildIndexSchema(IndexSchemaFactory.java:69) at org.apache.solr.core.CoreContainer.createFromLocal(CoreContainer.java:559) at org.apache.solr.core.CoreContainer.create(CoreContainer.java:597) at org.apache.solr.core.CoreContainer$1.call(CoreContainer.java:258) at org.apache.solr.core.CoreContainer$1.call(CoreContainer.java:250) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) ... 1 more Caused by: java.lang.RuntimeException: unknown field 'id' at org.apache.solr.schema.IndexSchema.getIndexedField(IndexSchema.java:340) at org.apache.solr.schema.IndexSchema.readSchema(IndexSchema.java:536) … -
getting error: 'Each option setting in configuration file must be a map ' while deploying django app in EBS
I am trying to deploy a django application in EBS. I am following the aws tutorial but I'm unable to deploy. The error says: 'ERROR: Each option setting in configuration file reclutapp_project/.ebextensions/django.config in application version app-db14-180308_133135 must be a map. Update each option setting in the configuration file.' This is my config file: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: reclutapp_project/reclutapp_project/wsgi.py And my file structure: reclutapp/ .ebextensions/ django.config reclutapp_project/ manage.py reclutapp_project/ urls.py wsgi.py I've ssh my ebs application and the wsgi.py path is correct. I've also tried this with no success. I've also checked indentation and format. I've also tried with json format getting the same error. I've deleted elastickbeanstalk config file and created a new environment, but nothing seems to work. I assume the problem relies on the config file format, but I'm using both yalm and json compatible formats. I am using Django 2.0 and Python 3.6 environment. Any suggestions? -
why it shows error that from . views can't be imported
music/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<album_id>[0-9)+$', views.detail, name='detail'), ] followed by views.py code from django.http import HttpResponse def index(request): return HttpResponse("this is something") def detail(request, album_id): return HttpResponse(" details of album " + str(album_id)+"") the main url website is built correctly..