Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to reset the password in DRF?
I'm working in AngularJS and Django Rest Framework project. I try to create API for reset password. I import SendPasswordResetEmail to my view. Code like this: class PasswordResetAPI(APIView): permission_classes = (AllowAny,) def post(self, request, format=None): data = request.data form = SendPasswordResetEmail(data) if form.is_valid(): form.send_mail() return Response({"message": "Send to reset password code in your email."}) return Response({"message": "Wrong email"}) I get {detail: "JSON parse error - Expecting value: line 1 column 1 (char 0)"} error. How to solve this problem? Thank you. -
Translations not persisting in Django
I've spent quite a few hours searching this site and other sites, and reading the Django documentation, but I have not yet been able to find a solution for my Django translation problem. I should add that I am a Django newbie, so apologise in advance if I'm doing something silly. I am using Django 1.10 and Python 3.5.2. My situation Every registered user for my application will have a language code assigned. This code will be stored in an extension of the django.contrib.auth.models User model (so UserExtend model, with 1-1 mapping to User). When a user logs in, I would like to read this language code and consequently translate all pages the user visits into that language. To do this, I am activating translations and storing the language code in a session variable. However, I find that after the user logs in and is redirected to another page, strings are not translated. If I log the user in but omit the redirection code (ie just present the login page again), strings are translated (I check this by creating a user with language_code 'de-DE' and creating and compiling dummy translations with _de prefixes), but as soon as I use my … -
Supervisor update Cant reread
Why I get this error? (venv) root@ProxyService:/etc/supervisor# supervisorctl update error: <class 'xmlrpclib.Fault'>, <Fault 92: "CANT_REREAD: The directory named as part of the path /home/proxy-service/logs/fcgi.log does not exist. in section 'program:proxy-service_fcgi' (file: '/etc/supervisor/supervisord.conf')">: file: /usr/lib/python2.7/xmlrpclib.py line: 800 Even if i create this log file, i get this error. -
Django custom Authentication and middleware
In my project I got Custom user model that inherits from AbstractBaseUser. class VerifiedUser(AbstractBaseUser, PermissionsMixin): Also I have my own authentication. I wrote it via implementing BaseAuthentication and putting it into 'DEFAULT_AUTHENTICATION_CLASSES': ( 'api.services.authentication_service.CustomTokenJsonAuthentication', ), I want to user my own middleware and I put it after 'django.contrib.auth.middleware.AuthenticationMiddleware', but request.user is always Anonymous and I see in debugger that it happens because AuthenticationMiddleware is executed before my CustomTokenJsonAuthentication Why does it happen and how can I put them in order? -
how to insert gap between rows of a table?
i want to add gap betweenw my input boxes in input form. They are heavily packed together and not looking good. so that the input form looks and feels good...form is a object passed from views.py.... createcustomer.html {% extends 'customer/base.html' %} {% block title %}Create Customer{% endblock %} {% block body %} <div class="container-fluid" style="background-color: #f2f2f2; width:100%; height:135%;" > <div class="row "> <div class="col-lg-4"></div> <div class="col-lg-8 text-left" align="center"> <h2>Create a Customer</h2> <form action="." method="post"> <div class="form-group" > {% csrf_token %} <table> <tr style="width:100%;" class="highlight"> <td>First Name:</td> <td>{{form.fname}}</td> </tr> <tr> <td>Last Name:</td> <td>{{form.lname}}</td> </tr> <tr> <td>Email:</td> <td>{{form.email}}</td> </tr> <tr> <td>Address:</td> <td>{{form.address}}</td> </tr> <tr> <td>City:</td> <td>{{form.city}}</td> </tr> <tr> <td>State:</td> <td>{{form.state}}</td> </tr> <tr> <td>Zip:</td> <td>{{form.zip}}</td> </tr> <tr> <td>Username:</td> <td>{{form.uname}}</td> </tr> <tr> <td>Phone:</td> <td>{{form.phone}}</td> </tr> </table> <div style="margin-left:200px; margin-top:20px;margin-bottom:20px"> <input type="submit" class="btn btn-success" value="Submit"> </div></div> </form> </div> </div> </div> {%endblock%} -
Django UpdateView create new object
My problem: UpdateView create new object instead of updating previous, i think its happens because in class definition of my view i override get_object method like this: def get_object(self, queryset=None): try: object_get = self.model.objects.get(pk=self.kwargs['pk']) except ObjectDoesNotExist: raise Http404("No object found matching this query") if self.request.user.is_authenticated(): if object_get.owner == self.request.user: return object_get And so if current user is not owner of the object - this method return nothing - its what i wanted, but my form class instead create new object: class ClientCreation(forms.ModelForm): class Meta: model = Client fields = ('name', 'loyal') I think this is happened because form doesn't receive a self.instance and create new instead - what should i do in this situation? I don't want new object to be created, in case when owner of object is not the current user i want nothing to happend then sending such a post request. How should i correctly implement this? -
Javascript not working after Datatable Filter or Paging
I am using Django ListView to display a list of invoices. I am trying to use Javascript to send updates. For example, when the invoice is paid, the user can click on the icon of the row and that invoice will be marked as paid. Everything is working well, but, I am using datatable to allow the user a secondary filtering. On page load, the javascript and call to server works fine, however, when filter or paging is used, Javascript is not picking up the row number. Just for simplicity, I test it with a alert() function - here's the html HTML: <table width="100%" class="table table-striped table-bordered table-hover" id="dt-invoice"> <thead> <tr> <th></th> <th>Inoice Number</th> <th>Description</th> <th>Date Sent</th> </tr> </thead> <tbody> {% csrf_token %} {% for i in invoice %} <tr id="{{ i.invoice }}"> <td><a id='id_paid-{{ i.id }}' title="I Got This!" href="#"><i class="fa fa-check fa-fw"></i></a></td> <td>i.invoice_number</td> <td>i.invoice_description</td> <td>i.invoice_sent_date</td> </tr> {% endfor %} </tbody> </table> Javascript: $(document).ready(function() { $('#dt-invoice').DataTable({ buttons: [ 'copy', 'csv', 'excel', 'pdf','print'], "iDisplayLength": 10, "processing": true, responsive: true, "dom": '<"top pull-left" li><"top pull-right" f> <t> <"bottom pull-left" iB><"bottom pull-right" p>', }); $('[id^=id_paid-]').click(function(){ console.log("HERE") row = $(this).closest('tr'); trid = row.attr("id"); alert(trid); }); }); Any ideas? Thanks in advance! -
Exclude a single field from migration
My model maps a table from existing database. I have a field referencing to another table, but in a source table there is no foreign key constraint. While there is managed=False flag in a Meta, class everything is all right, but I wanted to add a field in a model, so I need to remove this flag. From this moment I get an error as below: django.db.utils.ProgrammingError: column "<referencing_column_id>" of relation "<relation_name>" already exists I think solution would be setting managed=False flag for a single field. Is it actually a solution for this problem? If not, is there another way? -
Django Migrations - what benefits do they bring?
I am pretty sure that Django Migrations bring many benefits to the Django platform. I am just having a hard time identifying those benefits. Maybe someone could explain to me in what circumstances Django Migrations can be beneficial. In what way does it benefit the work of a software developer? I could not find that kind of information in the documentation. Maybe it is so obvious that there is no need. Anyway, thanks in advance for any hint. -
Choice field in django form becomes inactive
I have a model Branch containing CharField city: class Branch(models.Model): city = models.CharField(_('city'), max_length=SHORT_STRING, unique=True) I want to create a form with a drop-down list containing this field: class ContactForm(forms.Form): city = forms.ModelChoiceField(queryset=Branch.active_branches.all()) active_branches is a ModelManager, irrelevant here. Anyway, when I load the page with this form the field remains active for a while and then suddenly turns grey and can't be selected, or modified anymore: -
Get the value of last record of every month (Django)
My Model: class Transaction (models.Model): transaction_id = models.AutoField(primary_key=True) net_monthly_transaction = models.DecimalField(max_digits = 10, decimal_places = 2, default=0) # deposit or withdrawal (withdrawal with negative value) amount = models.DecimalField(max_digits = 10, decimal_places = 2) time_stamp = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): # __unicode__ on Python 2 return str(self.time_stamp) + str(self.amount) + str(self.net_monthly_transaction) My aim is to get the value of net_monthly_transaction from the last entry in every month. With help of S.O. I have managed to get this far: truncate_date = connection.ops.date_trunc_sql('month', 'time_stamp') lem = Transaction.objects.extra({'month':truncate_date}).values('month').annotate(last_record=Max('time_stamp')).values_list('net_monthly_transaction', flat=True) The above query is suppose to get the value of net_monthly_transaction from the max time_stamp in every month. But it doesn't. If I create three entries for October one after the other: net_monthly_transaction = 3000 net_monthly_transaction = 4000 net_monthly_transaction = 5000 all 3 values will be returned by the query. In the other hand: net_monthly_transaction = 3000 net_monthly_transaction = 2000 net_monthly_transaction = 1000 Then only the value 3000 is returned. So there is a condition set somewhere based on the size of the net_monthly_transaction. I am bit lost as to how I can solve this. Can someone please provide some direction. Thanks in advance. -
How to set dynamic many to many in factory boy with through table?
I'm having problems setting up a many to many relationship with a set of django models in factory boy, using a through relationship. I have a bunch of recipes and ingredients. There is a many-to-many relation between Recipes and Ingredients through a model that sets a quantity. I have factories for each model but cannot get them to link up. simplified models.py: class Ingredient(models.Model): name = models.CharField(max_length=40) class Recipe(models.Model): name = models.CharField(max_length=128) ingredients = models.ManyToManyField(Ingredient, through='RecipeIngredient') class RecipeIngredient(models.Model): recipe = models.ForeignKey(Recipe) ingredient = models.ForeignKey(Ingredient) quantity = models.IntegerField(default=1) simplified factories.py class RecipeFactory(factory.django.DjangoModelFactory): class Meta: model = Recipe class IngredientFactory(factory.django.DjangoModelFactory): class Meta: model = Ingredient class RecipeIngredientFactory(factory.django.DjangoModelFactory): class Meta: model = RecipeIngredient recipe = factory.SubFactory(RecipeFactory) ingredient = factory.SubFactory(IngredientFactory) quantity = 1 I've tried messing with factory.RelatedFactory but haven't really got anywhere. Ideally I just want to be able to do the following: recipe = RecipeFactory(name="recipe1") ingredient = IngredientFactory(name="ingredient1") ri = RecipeIngredientFactory(recipe=recipe, ingredient=ingredient) Doing this though does not set the many to many relation on either side, and also seems to fail to create the recipeingredient model itself. Does anyone know of a way to do this? -
Passing pattern to url
I want to map two or more seller to the same method ecommerce.views.seller. Below is the working code: urlpatterns = patterns('', url(r'^(store1|store3)/$', 'ecommerce.views.seller'), ) Is there any way by which I can declare some variable with pattern and simply pass it into urlpatterns. Something like: SELLER_ID = 'store1|store3' urlpatterns = patterns('', url(r'^(SELLER_ID)/$', 'ecommerce.views.seller'), ) -
unable to display foreign key relationship in Django rest framework
I have a model Project, Tasks, and Project has many Tasks, I'm trying to list all tasks under each project. GET /api/project/ HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "id": 2, "name": "Project 2", "task": [ 3 ] }, { "id": 1, "name": "Project 1", "task": [ 4, 2, 1 ] } ] I'm unable to display details of each Task, Task name, description, status ..etc Here is my Serializer from rest_framework.serializers import ModelSerializer from api.models import Project, Task class ProjectSerializer(ModelSerializer): class Meta: model = Project fields = ( 'id', 'name', 'task' ) class TaskSerializer(ModelSerializer): class Meta: model = Task Here is my Model from django.core.urlresolvers import reverse from django_extensions.db.fields import AutoSlugField from django.db.models import * from django.conf import settings from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.contrib.auth import get_user_model from django.contrib.auth import models as auth_models from django.db import models as models from django_extensions.db import fields as extension_fields from django.contrib.auth.models import User class Project(models.Model): # Fields user = models.ForeignKey(User) name = models.CharField(max_length=255) slug = extension_fields.AutoSlugField(populate_from='name', blank=True) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) # Relationship Fields #user = models.ForeignKey(settings.AUTH_USER_MODEL, ) user = models.ForeignKey(User) class Meta: ordering = ('-created',) def __unicode__(self): … -
Improve uwsgi performance by using specific parameters
I have a Django application running on a server using as interface uwsgi and nginx. I want to edit my uwsgi ini file in order to handle the memory better. I have very limited experience with uwsgi and I try to understand what's the best way to do this. I have read several different sources regarding the different parameters I can set in the ini file and I want a feedback if I am in the correct way or if you have any other suggestions for optimization. This is the list of parameters I want to add to my ini file: harakiri max-requests processes (which if I understand is the same with "workers") threads I understand that "harakiri" will spawn a process after a specified time. In many examples I saw that they use 20 sec. But how can I be sure that this is a good value to use? How can I monitor my uwsgi? max-requests: restarts processes automatically. Again, what would be an appropriate value? processes: refers to the amount of processes spawned to accept requests. Is it true that the greater the number, the more time will take to initialize? threads: I don't quite understand this parameter. … -
Django exclude field in admin if creator of this object is request user
how can i exclude field from Django admin if creator of this object is request user. is there any possible ways how to customise my model in admin.py? -
Django/FeinCMS ignores language/country specific url-name
we've got a Django (1.5.5) based application using FeinCMS (1.7.4). For a page formerly only the (general) en-based version was configured. Later specific configurations for en-us and en-ca were added, with different url-names (than used by the en version). This had the consequence that (en-based) links that had been distributed (via marketing channels) prior to that change, didn't work anymore. Playing around with the url-names I noticed, that Django/FeinCMS only honours the url-name which was edited last. Meaning, that ever only one url-name is recognised for all contexts (en, en-us and en-ca). The one which was edited/created last. Does someone know a way to fix this? I've tried to find the "responsible" code, but without success. Creating manual redirects is no option as there are too many links to specific stories/articles. -
Automatically play video on Mac
I've the following code in my webpage (Python/Django framework) to enable a video to play in the background. HTML <div class="video-container"> <div class="video-container-bg"> <video playsinline autoplay muted loop poster="{{page.image.url}}" id="bgvid"> <source src="{{page.video.url}}" type="video/mp4"> <source src="{{page.mac_video.url}}" type="video/webm"> </video> <div class="container"> <div class="row"> <div class="col-sm-12 col-md-8"> <div class="animation-element bounce-up"> <h1 class="page-title">{{page.page_title}}</h1> <p class="strapeline">{{page.strapline}}</p> <a class="butt" href="#about-us">Learn More</a> </div> </div> </div> </div> </div> </div> CSS video#bgvid { position: absolute; top: 50%; left: 50%; min-width: 100%; min-height:100%; overflow: hidden !important; z-index: -100; -ms-transform: translateX(-50%) translateY(-50%); -moz-transform: translateX(-50%) translateY(-50%); -webkit-transform: translateX(-50%) translateY(-50%); transform: translateX(-50%) translateY(-50%); background: url() no-repeat; background-size: 100%; } .video-container { min-height: calc(100vh - 75px); overflow: hidden !important; position: relative; } .video-container-bg { padding-top: 25vh; color: #fff; } It works fine on everything except a Mac where the background videos don't play. Why not? Is it something Apple have set to prevent? -
Need pagination in simple Django photo gallery
I am new to Django... I want to add pagination to my photo gallery app. I can't find how to do it and the django-pagination app does not work. models.py: class Photo(models.Model): photo_name = models.ImageField() date = models.DateTimeField('date') photo_text = models.CharField(max_length=200) collection = models.IntegerField(choices=COLLECTION_CHOICES) views.py: from django.template import RequestContext, loader from .models import Photo from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger def index(request): latest_photo_list = Photo.objects.order_by('-date')[:5] template = loader.get_template('photoweb/index.html') context = { 'latest_photo_list': latest_photo_list } return render(request, 'photoweb/index.html', context) def photopage(request, photo_id): photo = get_object_or_404(Photo, pk=photo_id) return render(request,'photoweb/photopage.html',{'photo': photo}) #(this view needs pagination) photopage.html: {% extends 'base.html' %} {% load staticfiles %} {% block content %} <div class="page-header"> <h1>{{ photo.photo_text }} <small>{{photo.get_collection_display}</small> </h1> </div> <body margin-bottom: 10px; > <div class="container"> <div class="row"> <div class="col-md-1"> <a class="navigation navigation-next" href="" aria-label="Previous photo" ><i class = "fa fa-angle-left"></i></a> </div> <div class="col-md-10" style="padding-left: 0px; padding-right:0px;"> <div class="photo"> <img src = "{% static photo.photo_name %}" alt = "Photo: {{photo.get_collection_display }} - {{photo.photo_text}}" > </div> </div> <div class="col-md-1"> <a class="navigation navigation-next" href="" aria-label="Next photo" ><i class = "fa fa-angle-right"></i></a> </div> </div> </body> {% endblock %} Note that the site works as-is, I have no problems loading the photographs or whatever. I just want to add "previous photo" … -
Django programming database
Pls, am trying to work on a movies site database where one can download movies but i need help on how d database setup should look like using django frame-work. Pls, am trying to work on a movies site database where one can download movies but i need help on how d database setup should look like using django frame-work. -
is a good way to use jinja replace django's template engine? what's the advantages and disadvantages?
It waste to much time when render templates by django's template engine. as we know jinja2 is much faster than that one. So if I use Jinja2, what's the advantages and disadvantages? -
Store boto3 session object in Django Session
I am trying to store boto3 session object in Django session so that I can reuse that same object as long Django session is available. This saves Auth requests for each operation I perform using boto3. boto3_session = boto3.Session(aws_access_key_id=request.POST.get("access_key"), aws_secret_access_key=request.POST.get("secret_key")) if not 'boto3_session' in request.session or not request.session['boto3_session']: request.session['boto3_session'] = boto3_session I am getting error TypeError: Session(region='eu-west-1') is not JSON serializable Details of boto3 session ipdb> dir(boto3_session) ipdb> ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_loader', '_register_default_handlers', '_session', '_setup_loader', 'client', 'events', 'get_available_partitions', 'get_available_regions', 'get_available_resources', 'get_available_services', 'get_credentials', 'profile_name', 'region_name', 'resource', 'resource_factory'] Trying to get dict for the object ipdb> boto3_session.__dict__ {'_loader': <botocore.loaders.Loader object at 0x104502450>, 'resource_factory': <boto3.resources.factory.ResourceFactory object at 0x1045023d0>, '_session': <botocore.session.Session object at 0x1044c6f50>} When I try to save above dict in session I get below error TypeError: <botocore.loaders.Loader object at 0x109e5dd10> is not JSON serializable How can I get this working. I am trying different things, but none are working so far. -
Django: model can be created without model field?
This is my code: class Order(TimeStampedModel): user = models.ForeignKey(settings.AUTH_USER_MODEL) merchant_uid = models.CharField(max_length=30, unique=True) imp_uid = models.CharField(max_length=30) from_cart = models.BooleanField() class Meta: ordering = ('-created',) def __str__(self): return self.merchant_uid But strange thing is, Order.objects.create(user=request.user, from_cart=True) works (in views.py). order = Order(user=request.user, from_cart=True) and order.save() also works. I didn't set blank=True and null=True on my merchant_uid, imp_uid fields, which means required field. But how is it possible to create model without those field?? -
ReactJS & django-forms
I have a modelform in django backend with validators, choicefields and etc. I would like to pass it to react and display it. First of all is that even possible? I would like to get it completly with validators, but just html is still great. The reason for that is: Avoiding double constant declarations on the front and back. For example select options: "male", "female", "???" would need to be on the backend for validation and frontend for display and validation. Constructing the whole html on the frontend for the form again, despite that all of it can also be easily created by django. Main concern again select options with many different custom values. There is a package called drf-braces that has a FormSerializer but it does seem to have a problem, I constantly get a 500 error "is not JSON serializable error", like in: name_or_event = CharFormSerializerField(error_messages={u'required': <django.utils.functional.__proxy__ object>}, help_text='', initial=None, label='Name', required=True, validators=[]) is not JSON serializable This is the drf-braces based serializer as seen in drf-braces form serialization example: from drf_braces.serializers.form_serializer import FormSerializer from myapp.forms import SignupDataForm class MySerializer(FormSerializer): class Meta(object): form = SignupDataForm and the API view based on rest-auth RegisterView: from myapp.serializers import MySerializer class … -
ImportError: No module named 'bs4' in django only
The same question has been asked a number of times but I couldn't find the solution. I am using BeautifulSoup and I am trying to import from bs4 import BeautifulSoup and I am getting error ImportError: No module named 'bs4' This error only comes in django. I am not able to figure out why this is happening. Screenshot attached.