Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why isn't strptime not working in my code?
I am using the following piece of code to populate my database. I've imported from datetime import datetime and is trying to create a datetime object to save to the DateTimeField of django. with open(os.path.join(settings.BASE_DIR, 'media', 'attendance', 'populate.csv')) as f: reader = csv.reader(f) for row in reader: obj, created = Attendance.objects.get_or_create( employee_id=row[0], punch=datetime.strptime(row[1], "%Y%m%d %H%M"), ) This is the error that I get. ValueError at /attn/populate/ time data ' 20170604 0600' does not match format '%Y%m%d %H%M' It seems like the string DOES match the format. What am I doing wrong here? -
Django - How to display time in web page according to user's time zone
I have new project in which i am sending datetime object in UTC std to the template. I want to display the time in user's time zone. This is because one user may be in USA another user may be in INDIA, so they have to view the time in their own time zone. In my django setting.py USE_TZ=True and TIME_ZONE="UTC". How can i make django to do this project. Please any one can help me with suitable code. -
Django: edit the choices set of forms.Select widget with dB data linked to current user in templates
Dear Python community, Could you please share some insights with a newbie like myself regarding the following topic: I would like to dynamically modify the inputs into form field input, specifically forms.ChoiceField(choices=((text, name), widget=forms.Select()) As I was not able to access requestfrom class in forms.py, I'd like to try editing the choices from Django template engine. Is it possible to edit the choices, taking the parameters from views.py method using jinja? The question is conceptual, a few lines of code as an example would be enough, I'll pick it up. The tricky part is - the data should be dependent on logged-in User's created model instances. If there's no actual way to do it via python, but js only - please let me know so I don't dry to do the impossible. Thank you! -
How to deal with a large queryset in Django
I need to process a queryset in Django of about 15 000 rows. I basically loop through the queryset and create a new object from each object in the queryset. The new object contains a number of calculated fields, as shown below. The result of the report is then saved as an Excel file, with one row for every CalcEntry. def get_report(report_date): for db_entry in my_large_queryset: yield CalcEntry(db_entry, report_date) class CalcEntry(object): def __init__(self, db_entry, report_date): self.db_entry = db_entry self.report_date = report_date @property def calc1(self): if self.db_entry.value_date > self.report_date return self.db_entry.value return 0 @property def calc2(self): #... There's about 20 of these calcs in the CalcEntry class Creating the report takes about 20s, so I'm close to getting a timeout error since it is running on Heroku (Heroku times out after 30s). However, just looping through the queryset takes a lot of time, without even creating the CalcEntry class. I read that looping through large querysets are not recommended, but I thought large would be more than 15 000. It looks like instead of looping through the queryset, I should use the values() method. Consequently, I thought of the following solutions, but all of them requires a lot of work so … -
Forloop counter with dynamic value range
I am using normal html table, and I am having more than 1000 records to display. So,I used pagination concept and make 100 results per page. The problem is, for the serial number column, Iam using forloop counter, for first page I got serial numbers as 1 to 100, for second page also I am getting serial numbers as 1 to 100. What I need is, it has to be 101 to 200 for second page and for third page it has to be 201 to 300, but it is showing 1 to 100. How to make serial number like I am expecting? -
Getting issues while fetching records from OrientDB using pyorient graph objects
I am new to OrientDB schema. I am using orientDB using pyorient.while inserting records in database working good, but while fetching records from database getting errors. Here is my code. For inserting records: from blipiq_django.settings import graph graph.create_vertex(Student, firstName=validated_data.get("first_name"), lastName=validated_data.get("last_name"), class_name=validated_data.get("class"), age=validated_data.get("age") ) Records inserted. For fetching records users = graph.query(Student).filter(Student.firstName == 'neelima').one() I am getting error like ERROR: com.orientechnologies.orient.core.sql.OCommandSQLParsingException - Error on parsing command at position #0: Error parsing query: SELECT FROM student WHERE firstName = 'neelima' Encountered " "@" "@ "" at line 1, column 33. Was expecting one of: <EOF> <AND> ... <OR> ... <ORDER> ... <GROUP> ... <LIMIT> ... <SKIP2> ... <OFFSET> ... <TIMEOUT> ... <FETCHPLAN> ... <LOCK> ... <NOCACHE> ... <PARALLEL> ... <UNWIND> ... ";" ... <AND> ... <OR> ... <GROUP> ... <ORDER> ... <UNWIND> ... <SKIP2> ... <OFFSET> ... <LIMIT> ... <FETCHPLAN> ... <TIMEOUT> ... <LOCK> ... <PARALLEL> ... <NOCACHE> ... <NOCACHE> ... I am using orientDB v.2.1.3 and pyorient 1.5.4 versions. Please any one can help me. Thanks in advance. -
Cannot Start Django in Docker
I am trying to run django-packages in Docker, but I am unable to. I am getting the following:- django_1 | Postgres is up - continuing... django_1 | python: can't open file 'manage.py': [Errno 2] No such file or directory django_1 | python: can't open file 'manage.py': [Errno 2] No such file or directory Everything seems to be fine though.The daemon is running. docker ps C:\djangopackages-master>docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES docker volume ls C:\djangopackages-master>docker volume ls DRIVER VOLUME NAME local djangopackagesmaster_postgres_backup_dev local djangopackagesmaster_postgres_data_dev local ef5505952d82c1472e74e21a8d2921018b2f7ee5570742268c8560335fe5762b Cant seem to figure out what might be the issue. -
UnicodeEncodeError 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)
I have views.py and models.py as follows , through the forms i have entered some non English characters(Other Regional Language), and saved to database . After submitting if i try to edit with my admin interface . Its giving the following error : UnicodeEncodeError 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128) Kindly suggest . Views.py def new_submit(request): if request.method == 'POST': form = NewsForm(request.POST) if form.is_valid(): c=form.save(commit=False) c.author = request.user c.save() return redirect(my_submitted_news ) else: form = NewsForm() return render(request,'new_submit.html', {'form': form}) models.py: class News_Post(models.Model): Country=models.CharField(max_length=20) State=models.CharField(max_length=20) District=models.CharField(max_length=20) Area=models.CharField(max_length=20) Photo_link=models.CharField(max_length=50,blank=True) News_Title=models.CharField(max_length=200) News=models.TextField() created_date=models.DateTimeField(auto_now_add=True,) author = models.CharField(max_length=20) def __str__(self): return self.News_Title -
which django permission package suits according to my need
There is builtin django permission and some other packages i have checked them out on https://djangopackages.org/grids/g/perms/. each permission package is suitable for what kind of authorization you want to achieve. I need to know is there any permission package that suits my need Here are my models class Shop(model): .... class Designation(model): name shop = model.ForeignKey(Shop) class UserProfile(model): user = model.OneToOneField(auth.User) type = model.ForeingKey(Designation) model.ManyToMany(Shop) class A(model): somecolum = CharField() othercolum = CharField() shop = model.ForeignKey(Shop) class B(model) somecolum = CharField() othercolum = CharField() shop = model.ForeignKey(Shop) Data: Shop1,Shop2,Shop3,Shopx User1,User2,User3,Userx Designation X, Designation Y, Desgination Z Here is what i am expecting: User1 can add,edit and view model A for Shop2 and Shop3 User2 can add,edit and view model A for Shop2 and can only view model A for Shop2 Userx can view modelA and modelB data for Shop1,Shop2 and Shop3 and Can add/edit/delete modelA and modelB for Shopx ideally User 1 has Designation X (and Designation X can add,edit and view model A for Shop2 and Shop3 like wise. -
Django rest framework request.data raises Error
I am using django rest framework. Bot in my view, there raises error like request instance has no attribute 'data' I tried a lot and doesnot fine anything. Do i have to add any middleware or something. How DRF retrieves data from request.POST and request.GET. My view is function based one. -
Get the host IP from my django app container
There is a feature on our web app that we need to send the IP of our server but I always send 172.17.0.2 because that is the value of request.META['REMOTE_ADDR'] which is usually 127.0.0.1 when using django in localhost and which I assume is the TCP address of our NodeJS container which where the request is coming from. How will I send the IP of my docker host instead? Containers: Nginx Django with gunicorn PostgreSQL Redis -
Self M2M with django- get_or_create
I am trying to create create a M2M value on self within the same model. I can update the name field fine. However, I keep getting the TypeError when I update the M2M (supertag) field. models.py class Tag(models.Model): name = models.CharField("Name", max_length=5000, blank=True) supertag = models.ManyToManyField('self', blank=True) serializers.py supe = tag.all() print(supe) # returns [<Tag: XYZ>, <Tag: 123>] for supertager in supe: # import pdb; pdb.set_trace() tag = Tag.objects.get_or_create(supertag__pk=supe.pk) tag.save() error: TypeError: 'supertag__pk' is an invalid keyword argument for this function I also tried just tag = Tag.objects.get_or_create(supertag=supe) which gave the same error -
Save Images from CSV to Django Image Field
I am building a simple image serving api using drf, the data is being imported from a csv This is my sample csv data title description image Item 1 Description 1 http://www.imgur.com/784/77987987.jpg Item 2 Description 2 http://www.image.com/images/797-oijio.jpg Item 3 Description 3 https://www.google.com/logo.jpg class Image(BaseModel): title = models.CharField(max_length=200, unique=True) description = models.CharField(max_length=400, null=True, blank=True) image = models.ImageField(null=True, blank=True) class Meta: db_table = 'images' def __str__(self): return self.title this is my image model, since I am using ImageField. I want to download the images from the url's in the image row inside the csv and then save them locally inside say /tmp/img and after that i want to programmatically save those images to Django ImageField right now i am only importing title and description to my models from the csv. What i want to do is , the respective image for the title should first be downloaded to the /tmp/img and then the respective local file should be added to image = models.ImageField(null=True, blank=True) so far i have done this and it doesn't work as expected import csv import requests import tempfile from os.path import basename from django.core.management.base import BaseCommand from django.core import files from images.models import Image class Command(BaseCommand): def add_arguments(self, … -
Django - How to allow inheritance of swappable model?
I am using swappable to make a reusable app (named Meat) that provides models that Developers can swap for their own. That model is a super class of other models. from django.db.models import Model, CharField from swapper import swappable_setting class AbstractMeat(Model): class Meta: abstract = True name = CharField(max_length=16) class Meat(AbstractMeat): class Meta: swappable = swappable_setting("cyber", "Meat") class Pork(Meat): pass class Fish(Meat): pass To test this, i created the real app and set MEAT_MEAT_MODEL. # settings.py MEAT_MEAT_MODEL = "real.RealMeat" # real/models.py from django.forms import IntegerField from cyber.models import AbstractMeat class RealMeat(AbstractMeat): price = IntegerField() Running runserver i get this error: meat.Fish.meat_ptr: (fields.E301) Field defines a relation with the model 'meat.Meat', which has been swapped out. HINT: Update the relation to point at 'settings.MEAT_MEAT_MODEL'. meat.Pork.meat_ptr: (fields.E301) Field defines a relation with the model 'meat.Meat', which has been swapped out. HINT: Update the relation to point at 'settings.MEAT_MEAT_MODEL'. This error arises on Django 1.9 to 1.11, but for my purpose only 1.11 is critical. I tried overriding the meat_ptr as instructed in Multi-table inheritance like so: from swapper import get_model_name from django.db.models import OneToOneField, CASCADE class Pork(Meat): meat_ptr = OneToOneField( get_model_name("meat", "Meat"), CASCADE, parent_link=True) But it gives me this error on 1.11 … -
Django POST request empty form HTML form
For some reason request.body and request.POST are both empty when I attempt to submit a simple HTML form. The HTML is: <div id="signup"> <h1>Sign Up for Free</h1> <form action="/accounts/register" method="POST"> <div class="top-row"> <div class="field-wrap"> <label> First Name<span class="req">*</span> </label> <input type="text" required autocomplete="off" /> </div> <div class="field-wrap"> <label> Last Name<span class="req">*</span> </label> <input type="text"required autocomplete="off"/> </div> </div> <div class="field-wrap"> <label> Email Address<span class="req">*</span> </label> <input type="email"required autocomplete="off"/> </div> <div class="field-wrap"> <label> Set A Password<span class="req">*</span> </label> <input type="password"required autocomplete="off"/> </div> <button type="submit" class="button button-block"/>Get Started</button> </form> </div> And the endpoint is: @api_view(['GET', 'POST']) def user_register(request): if request.method == 'GET': return render(request, 'authentication.html') elif request.method == 'POST': print("Register") print request.body print request.POST else: return render(request, '404.html') -
heroku can't find pip when I push app to it
When I try to push my django app to heroku it fails right at the beginning: remote: -----> Python app detected remote: -----> Installing python-3.5.1 remote: -----> Installing pip remote: -----> Installing requirements with pip remote: /app/tmp/buildpacks/779a8bbfbbe7e1b715476c0b23fc63a2103b3e4131eda558669aba8fb5e6e05682419376144189b29beb5dee6d7626b4d3385edb0954bffea6c67d8cf622fd51/ bin/steps/pip-install: line 5: /app/.heroku/python/bin/pip: No such file or directory remote: ! Push rejected, failed to compile Python app. remote: I apparently do something wrong, but I did the same thing many times before. What's wrong? -
I'm trying to link Heroku to our Django site and need help understanding this error log
2017-05-15T02:13:43.087131+00:00 heroku[web.1]: State changed from starting to crashed 2017-05-15T02:14:39.171624+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=newsrank-115.herokuapp.com request_id=18dfe977-391f-4873-88f5-d4d7f7f196a7 fwd="50.131.194.116" dyno= connect= service= status=503 bytes= protocol=https 2017-05-15T02:14:39.438971+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=newsrank-115.herokuapp.com request_id=5b31eda6-12e1-42bd-9b1a-53cd95dbc758 fwd="50.131.194.116" dyno= connect= service= status=503 bytes= protocol=https 2017-05-15T02:14:48.180441+00:00 heroku[web.1]: State changed from crashed to starting 2017-05-15T02:14:55.743399+00:00 heroku[web.1]: Starting process with command `gunicorn mysite.wsgi` 2017-05-15T02:14:57.785412+00:00 app[web.1]: [2017-05-15 02:14:57 +0000] [4] [INFO] Starting gunicorn 19.7.1 2017-05-15T02:14:57.786079+00:00 app[web.1]: [2017-05-15 02:14:57 +0000] [4] [INFO] Listening at: http://0.0.0.0:59306 (4) 2017-05-15T02:14:57.786293+00:00 app[web.1]: [2017-05-15 02:14:57 +0000] [4] [INFO] Using worker: sync 2017-05-15T02:14:57.789917+00:00 app[web.1]: [2017-05-15 02:14:57 +0000] [8] [INFO] Booting worker with pid: 8 2017-05-15T02:14:57.794048+00:00 app[web.1]: [2017-05-15 02:14:57 +0000] [8] [ERROR] Exception in worker process 2017-05-15T02:14:57.794050+00:00 app[web.1]: Traceback (most recent call last): 2017-05-15T02:14:57.794051+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 578, in spawn_worker 2017-05-15T02:14:57.794052+00:00 app[web.1]: worker.init_process() 2017-05-15T02:14:57.794052+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 126, in init_process 2017-05-15T02:14:57.794053+00:00 app[web.1]: self.load_wsgi() 2017-05-15T02:14:57.794054+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 135, in load_wsgi 2017-05-15T02:14:57.794054+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2017-05-15T02:14:57.794055+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi 2017-05-15T02:14:57.794056+00:00 app[web.1]: self.callable = self.load() 2017-05-15T02:14:57.794056+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 65, in load 2017-05-15T02:14:57.794057+00:00 app[web.1]: return self.load_wsgiapp() 2017-05-15T02:14:57.794058+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp 2017-05-15T02:14:57.794058+00:00 app[web.1]: return util.import_app(self.app_uri) 2017-05-15T02:14:57.794059+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 352, in import_app 2017-05-15T02:14:57.794059+00:00 … -
Calculate a number in a Django model from another model's data
I want to take data (amount_spent) from the field of each user and add those numbers up and display them in another field (total_revenue) from a different model (RevenueInfo). from __future__ import unicode_literals from django.contrib.auth.models import User from django.db import models from django import forms, views # Create your models here. #LoginInfo is being used, LoginForms in forms.py is class LoginInfo(models.Model): username = models.CharField('', max_length=10) password = models.CharField('', max_length=15) class ExtendedProfile(models.Model): user = models.OneToOneField(User) amount_spent = models.DecimalField(max_digits=6, decimal_places=2) class RevenueInfo(models.Model): total_amount_spent = models.DecimalField(max_digits=6, decimal_places=2, default=0) total_revenue = models.ForeignKey(ExtendedProfile, null=True) class Product(models.Model): category = models.CharField(max_length=100) name = models.CharField(max_length=100) description = models.TextField() #photo = models.ImageField() price_CAD = models.DecimalField(max_digits=6, decimal_places=2) quantity = models.DecimalField(max_digits=2, decimal_places=0, null=True) How could I go about this? Would I iterate of each Usermodel and find User.amount_spent then add that to RevenueInfo.total_revenue? I'm not sure how to put that into code. Also I'm pretty sure I don't need both total_amount_spent and 'total_revenuebut I feel like I need aForeignKey` -
How to use List of model in Django?
I'm trying to do like this: Class conversation(models.Model): user1, user2 =; # this is from User table messages = List(Message) # where Message is also a model Class Message(models.Model): sender, reciever ; # this is user ID from User Model ...... # many other attribute message = TextField() This is only a pseudo code. Anybody, please explain to me how to do this. If possible, give me a suitable tutorial link related to this. Thanks. -
DateFields not using custom DATE_FORMAT for output
I've followed Django's documentation in order to set the date output format for all the DateFields used in my project. Despite this, dates are still not being rendered in the format I'm enforcing. They're being outputted as YYYY-mm-dd instead. Here's my config: settings.py USE_L10N = False DATE_FORMAT = '%d/%m/%Y' SHORT_DATE_FORMAT = '%d/%m/%Y' DATE_INPUT_FORMATS = [ '%d/%m/%Y', # '25/10/2006' ] Is there something I'm missing here, or is this a bug with Django? -
How to handle behavioral changes of a model after introducing a new field?
I have a model/class with it's own methods to calculate some data. Recently i have to introduce a new boolean/choice field is_producing, based on that field calculation will be changed in multiple places, especially on property methods. Like below example: class Lease(models.Model): name = models.CharField(max_length=250) @property def owner_count(self): return 27 # for example class Lease(models.Model): name = models.CharField(max_length=250) is_producing = models.BooleanField(default=True) @property def owner_count(self): if self.is_producing: return 27 # for example else: return 20 # for example class Offer(models.Model): lease = models.ForeignKey(Lease) amount = models.FloatField() def save(self): if self.lease.is_producing: self.amount = 100 # For Example else: self.amount = 200 It seems that using if/else in all places is anti-pattern and not intuitive. On the other hand, if we create a new model with that new field, it will duplicate a lot of code and relate models. So i am looking for design pattern which can solve the above scenario or any other elegant solution that would solve it with less code duplication. -
get selected radio in Django
I want to know what radio is selected after clicking a submit button. my forms.py class forum(forms.Form): CHOICES = (('select1', 'select 1'), ('select2', 'select 2')) choix = forms.TypedChoiceField(choices=CHOICES, widget=forms.RadioSelect) query = forms.CharField(label='Product name',max_length=100,required=True) -
relation does not exist when launch my DJANGO APP in heroku
I'm doing an APP with django and I have a problem when I'm deploying it, on heroku PaaS. The problem is when I launch the app, I see the following error in my url:relation "calculadora_universidad" does not exist LINE 1: ...ad"."id", "calculadora_universidad"."nombre" FROM "calculado... exactly when try to access in universidad in the html template: <form method="POST" action="">{% csrf_token %} <h2>Utiliza la calculadora</h2> <!-- Calculadora --> <p><label for="basic-url">1. A que universidad y a que carrera quieres acceder?</label></p> <form> <select value ="Universidades" name="selectuniversidades" id="selectuniversidades" type="button" class="btn btn-default dropdown-toggle"> {% for e in universidades %} <option value="{{e.id}}">{{ e.nombre }}</option> <li role="separator" class="divider"></li> {% endfor %} </select><br><br> </form> This is because the tables of the models is not created, but I'm following all steps that the heroku center explains, and the last I have try is doing is put the postgres credenteials in my settings and try to migrate but I see the same problem. When I build the app following this steps: heroku link and I run the comand : heroku run python manage.py migrate (because the syncdb not work now) I don't see the creations of the table how I saw in the local deployment. I don't know why pass this, … -
Changing views automatically and alternately with Django and Celery
I'm making a django app that is going to change views automatically after 10 seconds in each views when open. There are 2 views only. I've never used Celery before, That's a test app that I'm gonna change to do a project. As you can see below, What i'm trying to do is to call the other view after 10 seconds and so on. But the only thing that is going on is that each view is renderd after exact 10 seconds when I type the url, They aren't changing alternately Any help is appreciated tasks.py from celery import shared_task from django.shortcuts import redirect from django.urls import reverse from django.core.urlresolvers import resolve import time @shared_task def open_view(request): current_url = resolve(request.path_info).url_name if current_url == 'view1': time.sleep(10) return redirect("view2") if current_url == 'view2': time.sleep(10) return redirect("view1") views.py from django.shortcuts import render from myapp.tasks import open_view # Create your views here. def view1(request): open_view(request) return render(request, 'view1.html') def view2(request): open_view(request) return render(request, 'view2.html') -
Django pagination - 5k objects
As a continuation of this question Django pagination with bootstrap any my works under my Contacts app I have to ask for your help once more. I have a problem I cannot resolve. I used few suggestions about pagination but all that is changing is the bottom pagination menu. My app is still loading all 5k objects every time, over and over. I am new at this, this app is my first project and this is the final 'big' missing part. I promiss to post final cone when I'm done :) Best regards. views.py `def index(request): contacts_list = contacts.objects.all() contacts_filter = LFilter(request.GET, queryset=contacts_list) paginator = Paginator(contacts_list, 50) try: page = int(request.GET.get('page','1')) except: page = 1 try: contacts = paginator.page(page) except PageNotAnInteger: contacts = paginator.page(1) except EmptyPage: contacts = paginator.page(paginator.num_pages) index = contacts.number - 1 max_index = len(paginator.page_range) start_index = index - 3 if index >= 3 else 0 end_index = index + 3 if index <= max_index - 3 else max_index page_range = paginator.page_range[start_index:end_index] return render( request, 'index.html', context={'filter': contacts_filter, 'contacts': contacts, 'page_range': page_range, } )` [1]: http://stackoverflow.com/questions/43574507/django-pagination-with-bootstrap [2]: http://stackoverflow.com/questions/30864011/display-only-some-of-the-page-numbers-by-django-pagination index.py {% for obj in filter.qs %} Code for contact information to display {% endfor %} <div class="prev_next"> {% if …